Line data Source code
1 : !--------------------------------------------------------------------------------------------------!
2 : ! CP2K: A general program to perform molecular dynamics simulations !
3 : ! Copyright 2000-2026 CP2K developers group <https://cp2k.org> !
4 : ! !
5 : ! SPDX-License-Identifier: GPL-2.0-or-later !
6 : !--------------------------------------------------------------------------------------------------!
7 : MODULE torch_api
8 : USE ISO_C_BINDING, ONLY: C_ASSOCIATED, &
9 : C_BOOL, &
10 : C_CHAR, &
11 : C_FLOAT, &
12 : C_DOUBLE, &
13 : C_F_POINTER, &
14 : C_INT, &
15 : C_NULL_CHAR, &
16 : C_NULL_PTR, &
17 : C_PTR, &
18 : C_INT32_T, &
19 : C_INT64_T
20 :
21 : USE kinds, ONLY: sp, int_4, int_8, dp, default_string_length
22 :
23 : #include "./base/base_uses.f90"
24 :
25 : IMPLICIT NONE
26 :
27 : PRIVATE
28 :
29 : TYPE torch_tensor_type
30 : PRIVATE
31 : TYPE(C_PTR) :: c_ptr = C_NULL_PTR
32 : END TYPE torch_tensor_type
33 :
34 : TYPE torch_dict_type
35 : PRIVATE
36 : TYPE(C_PTR) :: c_ptr = C_NULL_PTR
37 : END TYPE torch_dict_type
38 :
39 : TYPE torch_model_type
40 : PRIVATE
41 : TYPE(C_PTR) :: c_ptr = C_NULL_PTR
42 : END TYPE torch_model_type
43 :
44 : #:set max_dim = 3
45 : INTERFACE torch_tensor_from_array
46 : #:for ndims in range(1, max_dim+1)
47 : MODULE PROCEDURE torch_tensor_from_array_int32_${ndims}$d
48 : MODULE PROCEDURE torch_tensor_from_array_float_${ndims}$d
49 : MODULE PROCEDURE torch_tensor_from_array_int64_${ndims}$d
50 : MODULE PROCEDURE torch_tensor_from_array_double_${ndims}$d
51 : #:endfor
52 : END INTERFACE torch_tensor_from_array
53 :
54 : INTERFACE torch_tensor_reset_from_array
55 : #:for ndims in range(1, max_dim+1)
56 : MODULE PROCEDURE torch_tensor_reset_from_array_double_${ndims}$d
57 : #:endfor
58 : END INTERFACE torch_tensor_reset_from_array
59 :
60 : INTERFACE torch_tensor_data_ptr
61 : #:for ndims in range(1, max_dim+1)
62 : MODULE PROCEDURE torch_tensor_data_ptr_int32_${ndims}$d
63 : MODULE PROCEDURE torch_tensor_data_ptr_float_${ndims}$d
64 : MODULE PROCEDURE torch_tensor_data_ptr_int64_${ndims}$d
65 : MODULE PROCEDURE torch_tensor_data_ptr_double_${ndims}$d
66 : #:endfor
67 : END INTERFACE torch_tensor_data_ptr
68 :
69 : INTERFACE torch_model_get_attr
70 : MODULE PROCEDURE torch_model_get_attr_string
71 : MODULE PROCEDURE torch_model_get_attr_double
72 : MODULE PROCEDURE torch_model_get_attr_int64
73 : MODULE PROCEDURE torch_model_get_attr_int32
74 : MODULE PROCEDURE torch_model_get_attr_strlist
75 : END INTERFACE torch_model_get_attr
76 :
77 : PUBLIC :: torch_tensor_type, torch_tensor_expand_dim, torch_tensor_from_array, &
78 : torch_tensor_narrow, torch_tensor_release
79 : PUBLIC :: torch_tensor_reset_from_array
80 : PUBLIC :: torch_tensor_data_ptr, torch_tensor_backward, torch_tensor_backward_scalar
81 : PUBLIC :: torch_tensor_grad, torch_tensor_grad_batch3
82 : PUBLIC :: torch_tensor_hessian_vector
83 : PUBLIC :: torch_tensor_to_device_leaf
84 : PUBLIC :: torch_tensor_item_double, torch_tensor_weighted_sum
85 : PUBLIC :: torch_dict_type, torch_dict_clone, torch_dict_create, torch_dict_insert
86 : PUBLIC :: torch_dict_get, torch_dict_release
87 : PUBLIC :: torch_model_type, torch_model_load, torch_model_load_with_metadata, &
88 : torch_model_forward, torch_model_release
89 : PUBLIC :: torch_model_disable_parameter_gradients, torch_model_forward_mol_tensor, &
90 : torch_model_remap_device_constants
91 : PUBLIC :: torch_model_promote_float32
92 : PUBLIC :: torch_model_prepare_higher_derivatives
93 : PUBLIC :: torch_model_get_attr, torch_model_read_metadata
94 : PUBLIC :: torch_cuda_device_count, torch_cuda_is_available
95 : PUBLIC :: torch_allow_tf32, torch_model_freeze, torch_model_freeze_preserving_method, &
96 : torch_use_cuda, torch_get_use_cuda
97 :
98 : CONTAINS
99 :
100 : #:set typenames = ['int32', 'float', 'int64', 'double']
101 : #:set types_f = ['INTEGER(kind=int_4)', 'REAL(sp)', 'INTEGER(kind=int_8)', 'REAL(dp)']
102 : #:set types_c = ['INTEGER(kind=C_INT32_T)', 'REAL(kind=C_FLOAT)', 'INTEGER(kind=C_INT64_T)', 'REAL(kind=C_DOUBLE)']
103 :
104 : #:for ndims in range(1, max_dim+1)
105 : #:for typename, type_f, type_c in zip(typenames, types_f, types_c)
106 :
107 : ! **************************************************************************************************
108 : !> \brief Creates a Torch tensor from an array. The passed array has to outlive the tensor!
109 : !> The source must be an ALLOCATABLE to prevent passing a temporary array.
110 : !> \author Ole Schuett
111 : ! **************************************************************************************************
112 2734 : SUBROUTINE torch_tensor_from_array_${typename}$_${ndims}$d(tensor, source, requires_grad)
113 : TYPE(torch_tensor_type), INTENT(INOUT) :: tensor
114 : #:set arraydims = ", ".join(":" for i in range(ndims))
115 : ${type_f}$, DIMENSION(${arraydims}$), ALLOCATABLE, INTENT(IN) :: source
116 : LOGICAL, OPTIONAL, INTENT(IN) :: requires_grad
117 :
118 : #if defined(__LIBTORCH)
119 : INTEGER(kind=int_8), DIMENSION(${ndims}$) :: sizes_c
120 : LOGICAL :: my_req_grad
121 :
122 : INTERFACE
123 : SUBROUTINE torch_c_tensor_from_array_${typename}$ (tensor, req_grad, ndims, sizes, source) &
124 : BIND(C, name="torch_c_tensor_from_array_${typename}$")
125 : IMPORT :: C_PTR, C_INT, C_INT32_T, C_INT64_T, C_FLOAT, C_DOUBLE, C_BOOL
126 : TYPE(C_PTR) :: tensor
127 : LOGICAL(kind=C_BOOL), VALUE :: req_grad
128 : INTEGER(kind=C_INT), VALUE :: ndims
129 : INTEGER(kind=C_INT64_T), DIMENSION(*) :: sizes
130 : ${type_c}$, DIMENSION(*) :: source
131 : END SUBROUTINE torch_c_tensor_from_array_${typename}$
132 : END INTERFACE
133 :
134 2734 : my_req_grad = .FALSE.
135 2734 : IF (PRESENT(requires_grad)) my_req_grad = requires_grad
136 :
137 : #:for axis in range(ndims)
138 2734 : sizes_c(${axis + 1}$) = SIZE(source, ${ndims - axis}$) ! C arrays are stored row-major.
139 : #:endfor
140 :
141 2734 : CPASSERT(.NOT. C_ASSOCIATED(tensor%c_ptr))
142 : CALL torch_c_tensor_from_array_${typename}$ (tensor=tensor%c_ptr, &
143 : req_grad=LOGICAL(my_req_grad, C_BOOL), &
144 : ndims=${ndims}$, &
145 : sizes=sizes_c, &
146 2734 : source=source)
147 2734 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
148 : #else
149 : CPABORT("CP2K compiled without the Torch library.")
150 : MARK_USED(tensor)
151 : MARK_USED(source)
152 : MARK_USED(requires_grad)
153 : #endif
154 2734 : END SUBROUTINE torch_tensor_from_array_${typename}$_${ndims}$d
155 :
156 : ! **************************************************************************************************
157 : !> \brief Copies data from a Torch tensor to an array.
158 : !> The returned pointer is only valide during the tensor's lifetime!
159 : !> \author Ole Schuett
160 : ! **************************************************************************************************
161 1354 : SUBROUTINE torch_tensor_data_ptr_${typename}$_${ndims}$d(tensor, data_ptr)
162 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
163 : #:set arraydims = ", ".join(":" for i in range(ndims))
164 : ${type_f}$, DIMENSION(${arraydims}$), POINTER :: data_ptr
165 :
166 : #if defined(__LIBTORCH)
167 : INTEGER(kind=int_8), DIMENSION(${ndims}$) :: sizes_f, sizes_c
168 : TYPE(C_PTR) :: data_ptr_c
169 :
170 : INTERFACE
171 : SUBROUTINE torch_c_tensor_data_ptr_${typename}$ (tensor, ndims, sizes, data_ptr) &
172 : BIND(C, name="torch_c_tensor_data_ptr_${typename}$")
173 : IMPORT :: C_CHAR, C_PTR, C_INT, C_INT32_T, C_INT64_T
174 : TYPE(C_PTR), VALUE :: tensor
175 : INTEGER(kind=C_INT), VALUE :: ndims
176 : INTEGER(kind=C_INT64_T), DIMENSION(*) :: sizes
177 : TYPE(C_PTR) :: data_ptr
178 : END SUBROUTINE torch_c_tensor_data_ptr_${typename}$
179 : END INTERFACE
180 :
181 4326 : sizes_c(:) = -1
182 1354 : data_ptr_c = C_NULL_PTR
183 1354 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
184 1354 : CPASSERT(.NOT. ASSOCIATED(data_ptr))
185 : CALL torch_c_tensor_data_ptr_${typename}$ (tensor=tensor%c_ptr, &
186 : ndims=${ndims}$, &
187 : sizes=sizes_c, &
188 1354 : data_ptr=data_ptr_c)
189 :
190 : #:for axis in range(ndims)
191 1354 : sizes_f(${axis + 1}$) = sizes_c(${ndims - axis}$) ! C arrays are stored row-major.
192 : #:endfor
193 :
194 4326 : IF (ALL(sizes_f /= 0)) THEN ! Torch returns null pointer for zero-sized tensors.
195 1354 : CPASSERT(C_ASSOCIATED(data_ptr_c))
196 4326 : CALL C_F_POINTER(data_ptr_c, data_ptr, shape=sizes_f)
197 : END IF
198 : #else
199 : CPABORT("CP2K compiled without the Torch library.")
200 : MARK_USED(tensor)
201 : MARK_USED(data_ptr)
202 : #endif
203 1354 : END SUBROUTINE torch_tensor_data_ptr_${typename}$_${ndims}$d
204 :
205 : #:endfor
206 : #:endfor
207 :
208 : #:for ndims in range(1, max_dim+1)
209 :
210 : ! **************************************************************************************************
211 : !> \brief Reuses or creates a device leaf tensor and copies data into it.
212 : !> The source must be an ALLOCATABLE to prevent passing a temporary array.
213 : ! **************************************************************************************************
214 318 : SUBROUTINE torch_tensor_reset_from_array_double_${ndims}$d(tensor, source, requires_grad, &
215 : reallocated)
216 : TYPE(torch_tensor_type), INTENT(INOUT) :: tensor
217 : #:set arraydims = ", ".join(":" for i in range(ndims))
218 : REAL(dp), DIMENSION(${arraydims}$), ALLOCATABLE, INTENT(IN) :: source
219 : LOGICAL, OPTIONAL, INTENT(IN) :: requires_grad
220 : LOGICAL, OPTIONAL, INTENT(OUT) :: reallocated
221 :
222 : #if defined(__LIBTORCH)
223 : INTEGER(kind=int_8), DIMENSION(${ndims}$) :: sizes_c
224 : LOGICAL :: my_req_grad
225 : LOGICAL(kind=C_BOOL) :: reallocated_c
226 :
227 : INTERFACE
228 : FUNCTION torch_c_tensor_reset_from_array_double_status(tensor, req_grad, ndims, sizes, source) &
229 : RESULT(reallocated_flag) BIND(C, name="torch_c_tensor_reset_from_array_double_status")
230 : IMPORT :: C_PTR, C_INT, C_INT64_T, C_DOUBLE, C_BOOL
231 : TYPE(C_PTR) :: tensor
232 : LOGICAL(kind=C_BOOL), VALUE :: req_grad
233 : INTEGER(kind=C_INT), VALUE :: ndims
234 : INTEGER(kind=C_INT64_T), DIMENSION(*) :: sizes
235 : REAL(kind=C_DOUBLE), DIMENSION(*) :: source
236 : LOGICAL(kind=C_BOOL) :: reallocated_flag
237 : END FUNCTION torch_c_tensor_reset_from_array_double_status
238 : END INTERFACE
239 :
240 318 : my_req_grad = .FALSE.
241 318 : IF (PRESENT(requires_grad)) my_req_grad = requires_grad
242 :
243 : #:for axis in range(ndims)
244 318 : sizes_c(${axis + 1}$) = SIZE(source, ${ndims - axis}$) ! C arrays are stored row-major.
245 : #:endfor
246 :
247 : reallocated_c = torch_c_tensor_reset_from_array_double_status( &
248 : tensor=tensor%c_ptr, &
249 : req_grad=LOGICAL(my_req_grad, C_BOOL), &
250 : ndims=${ndims}$, &
251 : sizes=sizes_c, &
252 318 : source=source)
253 318 : IF (PRESENT(reallocated)) reallocated = reallocated_c
254 318 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
255 : #else
256 : CPABORT("CP2K compiled without the Torch library.")
257 : MARK_USED(tensor)
258 : MARK_USED(source)
259 : MARK_USED(requires_grad)
260 : MARK_USED(reallocated)
261 : #endif
262 318 : END SUBROUTINE torch_tensor_reset_from_array_double_${ndims}$d
263 :
264 : #:endfor
265 :
266 : ! **************************************************************************************************
267 : !> \brief Creates an expanded tensor view along one singleton dimension.
268 : ! **************************************************************************************************
269 102 : SUBROUTINE torch_tensor_expand_dim(tensor, dim, extent, result)
270 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
271 : INTEGER, INTENT(IN) :: dim, extent
272 : TYPE(torch_tensor_type), INTENT(INOUT) :: result
273 :
274 : #if defined(__LIBTORCH)
275 : INTERFACE
276 : SUBROUTINE torch_c_tensor_expand_dim(tensor, dim, extent, result) &
277 : BIND(C, name="torch_c_tensor_expand_dim")
278 : IMPORT :: C_INT64_T, C_PTR
279 : TYPE(C_PTR), VALUE :: tensor
280 : INTEGER(kind=C_INT64_T), VALUE :: dim, extent
281 : TYPE(C_PTR) :: result
282 : END SUBROUTINE torch_c_tensor_expand_dim
283 : END INTERFACE
284 :
285 102 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
286 102 : CPASSERT(.NOT. C_ASSOCIATED(result%c_ptr))
287 102 : CPASSERT(dim >= 0)
288 102 : CPASSERT(extent >= 0)
289 : CALL torch_c_tensor_expand_dim(tensor=tensor%c_ptr, &
290 : dim=INT(dim, C_INT64_T), &
291 : extent=INT(extent, C_INT64_T), &
292 102 : result=result%c_ptr)
293 102 : CPASSERT(C_ASSOCIATED(result%c_ptr))
294 : #else
295 : CPABORT("CP2K compiled without the Torch library.")
296 : MARK_USED(tensor)
297 : MARK_USED(dim)
298 : MARK_USED(extent)
299 : MARK_USED(result)
300 : #endif
301 102 : END SUBROUTINE torch_tensor_expand_dim
302 :
303 : ! **************************************************************************************************
304 : !> \brief Creates a view of a contiguous tensor slice.
305 : ! **************************************************************************************************
306 1888 : SUBROUTINE torch_tensor_narrow(tensor, dim, start_index, length, result)
307 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
308 : INTEGER, INTENT(IN) :: dim, start_index, length
309 : TYPE(torch_tensor_type), INTENT(INOUT) :: result
310 :
311 : #if defined(__LIBTORCH)
312 : INTERFACE
313 : SUBROUTINE torch_c_tensor_narrow(tensor, dim, start_index, length, result) &
314 : BIND(C, name="torch_c_tensor_narrow")
315 : IMPORT :: C_INT64_T, C_PTR
316 : TYPE(C_PTR), VALUE :: tensor
317 : INTEGER(kind=C_INT64_T), VALUE :: dim, start_index, length
318 : TYPE(C_PTR) :: result
319 : END SUBROUTINE torch_c_tensor_narrow
320 : END INTERFACE
321 :
322 1888 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
323 1888 : CPASSERT(.NOT. C_ASSOCIATED(result%c_ptr))
324 1888 : CPASSERT(dim >= 0)
325 1888 : CPASSERT(start_index >= 0)
326 1888 : CPASSERT(length >= 0)
327 : CALL torch_c_tensor_narrow(tensor=tensor%c_ptr, &
328 : dim=INT(dim, C_INT64_T), &
329 : start_index=INT(start_index, C_INT64_T), &
330 : length=INT(length, C_INT64_T), &
331 1888 : result=result%c_ptr)
332 1888 : CPASSERT(C_ASSOCIATED(result%c_ptr))
333 : #else
334 : CPABORT("CP2K compiled without the Torch library.")
335 : MARK_USED(tensor)
336 : MARK_USED(dim)
337 : MARK_USED(start_index)
338 : MARK_USED(length)
339 : MARK_USED(result)
340 : #endif
341 1888 : END SUBROUTINE torch_tensor_narrow
342 :
343 : ! **************************************************************************************************
344 : !> \brief Runs autograd on a Torch tensor.
345 : !> \author Ole Schuett
346 : ! **************************************************************************************************
347 6 : SUBROUTINE torch_tensor_backward(tensor, outer_grad)
348 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
349 : TYPE(torch_tensor_type), INTENT(IN) :: outer_grad
350 :
351 : #if defined(__LIBTORCH)
352 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_tensor_backward'
353 : INTEGER :: handle
354 :
355 : INTERFACE
356 : SUBROUTINE torch_c_tensor_backward(tensor, outer_grad) &
357 : BIND(C, name="torch_c_tensor_backward")
358 : IMPORT :: C_CHAR, C_PTR
359 : TYPE(C_PTR), VALUE :: tensor
360 : TYPE(C_PTR), VALUE :: outer_grad
361 : END SUBROUTINE torch_c_tensor_backward
362 : END INTERFACE
363 :
364 6 : CALL timeset(routineN, handle)
365 6 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
366 6 : CPASSERT(C_ASSOCIATED(outer_grad%c_ptr))
367 6 : CALL torch_c_tensor_backward(tensor=tensor%c_ptr, outer_grad=outer_grad%c_ptr)
368 6 : CALL timestop(handle)
369 : #else
370 : CPABORT("CP2K compiled without the Torch library.")
371 : MARK_USED(tensor)
372 : MARK_USED(outer_grad)
373 : #endif
374 6 : END SUBROUTINE torch_tensor_backward
375 :
376 : ! **************************************************************************************************
377 : !> \brief Apply the Hessian of a scalar tensor to its input directions.
378 : ! **************************************************************************************************
379 2 : SUBROUTINE torch_tensor_hessian_vector(tensor, inputs, directions, responses, status, to_host)
380 : TYPE(torch_tensor_type), INTENT(IN) :: tensor, inputs(:), directions(:)
381 : TYPE(torch_tensor_type), INTENT(INOUT) :: responses(:)
382 : INTEGER, OPTIONAL, INTENT(OUT) :: status
383 : LOGICAL, OPTIONAL, INTENT(IN) :: to_host
384 : #if defined(__LIBTORCH)
385 4 : TYPE(C_PTR) :: input_ptrs(SIZE(inputs)), &
386 4 : direction_ptrs(SIZE(inputs)), response_ptrs(SIZE(inputs))
387 : INTEGER :: i
388 : INTEGER(C_INT) :: c_status
389 : LOGICAL :: host
390 : INTERFACE
391 : SUBROUTINE torch_c_tensor_hessian_vector(tensor, count, inputs, directions, responses, to_host, status) &
392 : BIND(C, name="torch_c_tensor_hessian_vector")
393 : IMPORT :: C_INT, C_PTR, C_BOOL
394 : TYPE(C_PTR), VALUE :: tensor
395 : INTEGER(C_INT), VALUE :: count
396 : TYPE(C_PTR), INTENT(IN) :: inputs(*), directions(*)
397 : TYPE(C_PTR), INTENT(OUT) :: responses(*)
398 : LOGICAL(C_BOOL), VALUE :: to_host
399 : INTEGER(C_INT), INTENT(OUT) :: status
400 : END SUBROUTINE torch_c_tensor_hessian_vector
401 : END INTERFACE
402 2 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
403 2 : CPASSERT(SIZE(inputs) > 0)
404 2 : CPASSERT(SIZE(directions) == SIZE(inputs))
405 2 : CPASSERT(SIZE(responses) == SIZE(inputs))
406 8 : DO i = 1, SIZE(inputs)
407 6 : CPASSERT(C_ASSOCIATED(inputs(i)%c_ptr))
408 6 : CPASSERT(C_ASSOCIATED(directions(i)%c_ptr))
409 6 : CPASSERT(.NOT. C_ASSOCIATED(responses(i)%c_ptr))
410 6 : input_ptrs(i) = inputs(i)%c_ptr
411 8 : direction_ptrs(i) = directions(i)%c_ptr
412 : END DO
413 8 : response_ptrs = C_NULL_PTR
414 2 : host = .TRUE.
415 2 : IF (PRESENT(to_host)) host = to_host
416 : CALL torch_c_tensor_hessian_vector(tensor%c_ptr, INT(SIZE(inputs), C_INT), &
417 2 : input_ptrs, direction_ptrs, response_ptrs, LOGICAL(host, C_BOOL), c_status)
418 2 : IF (PRESENT(status)) THEN
419 0 : status = c_status
420 : ELSE
421 2 : CPASSERT(c_status == 0)
422 : END IF
423 8 : DO i = 1, SIZE(inputs)
424 6 : responses(i)%c_ptr = response_ptrs(i)
425 8 : IF (c_status == 0) THEN
426 6 : CPASSERT(C_ASSOCIATED(responses(i)%c_ptr))
427 : END IF
428 : END DO
429 : #else
430 : MARK_USED(tensor)
431 : MARK_USED(inputs)
432 : MARK_USED(directions)
433 : MARK_USED(responses)
434 : MARK_USED(status)
435 : MARK_USED(to_host)
436 : CPABORT("CP2K was compiled without LibTorch support.")
437 : #endif
438 2 : END SUBROUTINE torch_tensor_hessian_vector
439 :
440 : ! **************************************************************************************************
441 : !> \brief Runs autograd on a scalar Torch tensor.
442 : ! **************************************************************************************************
443 340 : SUBROUTINE torch_tensor_backward_scalar(tensor)
444 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
445 :
446 : #if defined(__LIBTORCH)
447 : INTERFACE
448 : SUBROUTINE torch_c_tensor_backward_scalar(tensor) &
449 : BIND(C, name="torch_c_tensor_backward_scalar")
450 : IMPORT :: C_PTR
451 : TYPE(C_PTR), VALUE :: tensor
452 : END SUBROUTINE torch_c_tensor_backward_scalar
453 : END INTERFACE
454 :
455 340 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
456 340 : CALL torch_c_tensor_backward_scalar(tensor=tensor%c_ptr)
457 : #else
458 : CPABORT("CP2K compiled without the Torch library.")
459 : MARK_USED(tensor)
460 : #endif
461 340 : END SUBROUTINE torch_tensor_backward_scalar
462 :
463 : ! **************************************************************************************************
464 : !> \brief Moves a tensor to the active Torch device and makes it an autograd leaf.
465 : ! **************************************************************************************************
466 2472 : SUBROUTINE torch_tensor_to_device_leaf(tensor, requires_grad)
467 : TYPE(torch_tensor_type), INTENT(INOUT) :: tensor
468 : LOGICAL, INTENT(IN) :: requires_grad
469 :
470 : #if defined(__LIBTORCH)
471 : INTERFACE
472 : SUBROUTINE torch_c_tensor_to_device_leaf(tensor, req_grad) &
473 : BIND(C, name="torch_c_tensor_to_device_leaf")
474 : IMPORT :: C_BOOL, C_PTR
475 : TYPE(C_PTR) :: tensor
476 : LOGICAL(kind=C_BOOL), VALUE :: req_grad
477 : END SUBROUTINE torch_c_tensor_to_device_leaf
478 : END INTERFACE
479 :
480 2472 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
481 : CALL torch_c_tensor_to_device_leaf(tensor=tensor%c_ptr, &
482 2472 : req_grad=LOGICAL(requires_grad, C_BOOL))
483 2472 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
484 : #else
485 : CPABORT("CP2K compiled without the Torch library.")
486 : MARK_USED(tensor)
487 : MARK_USED(requires_grad)
488 : #endif
489 2472 : END SUBROUTINE torch_tensor_to_device_leaf
490 :
491 : ! **************************************************************************************************
492 : !> \brief Select whether Torch wrappers should use CUDA when available.
493 : ! **************************************************************************************************
494 724 : SUBROUTINE torch_use_cuda(use_cuda)
495 : LOGICAL, INTENT(IN) :: use_cuda
496 :
497 : #if defined(__LIBTORCH)
498 : INTERFACE
499 : SUBROUTINE torch_c_use_cuda(use_cuda) BIND(C, name="torch_c_use_cuda")
500 : IMPORT :: C_BOOL
501 : LOGICAL(kind=C_BOOL), VALUE :: use_cuda
502 : END SUBROUTINE torch_c_use_cuda
503 : END INTERFACE
504 :
505 724 : CALL torch_c_use_cuda(use_cuda=LOGICAL(use_cuda, C_BOOL))
506 : #else
507 : MARK_USED(use_cuda)
508 : #endif
509 724 : END SUBROUTINE torch_use_cuda
510 :
511 : ! **************************************************************************************************
512 : !> \brief Return whether Torch wrappers currently select CUDA when available.
513 : ! **************************************************************************************************
514 360 : FUNCTION torch_get_use_cuda() RESULT(use_cuda)
515 : LOGICAL :: use_cuda
516 :
517 : #if defined(__LIBTORCH)
518 : INTERFACE
519 : FUNCTION torch_c_get_use_cuda() BIND(C, name="torch_c_get_use_cuda")
520 : IMPORT :: C_BOOL
521 : LOGICAL(kind=C_BOOL) :: torch_c_get_use_cuda
522 : END FUNCTION torch_c_get_use_cuda
523 : END INTERFACE
524 :
525 360 : use_cuda = torch_c_get_use_cuda()
526 : #else
527 : use_cuda = .FALSE.
528 : #endif
529 360 : END FUNCTION torch_get_use_cuda
530 :
531 : ! **************************************************************************************************
532 : !> \brief Returns the gradient of a Torch tensor which was computed by autograd.
533 : !> \author Ole Schuett
534 : ! **************************************************************************************************
535 256 : SUBROUTINE torch_tensor_grad(tensor, grad)
536 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
537 : TYPE(torch_tensor_type), INTENT(INOUT) :: grad
538 :
539 : #if defined(__LIBTORCH)
540 : INTERFACE
541 : SUBROUTINE torch_c_tensor_grad(tensor, grad) &
542 : BIND(C, name="torch_c_tensor_grad")
543 : IMPORT :: C_PTR
544 : TYPE(C_PTR), VALUE :: tensor
545 : TYPE(C_PTR) :: grad
546 : END SUBROUTINE torch_c_tensor_grad
547 : END INTERFACE
548 :
549 256 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
550 256 : CPASSERT(.NOT. C_ASSOCIATED(grad%c_ptr))
551 256 : CALL torch_c_tensor_grad(tensor=tensor%c_ptr, grad=grad%c_ptr)
552 256 : CPASSERT(C_ASSOCIATED(grad%c_ptr))
553 : #else
554 : CPABORT("CP2K compiled without the Torch library.")
555 : MARK_USED(tensor)
556 : MARK_USED(grad)
557 : #endif
558 256 : END SUBROUTINE torch_tensor_grad
559 :
560 : ! **************************************************************************************************
561 : !> \brief Copies three autograd gradients to CPU memory.
562 : ! **************************************************************************************************
563 338 : SUBROUTINE torch_tensor_grad_batch3(tensor1, tensor2, tensor3, grad1, grad2, grad3)
564 : TYPE(torch_tensor_type), INTENT(IN) :: tensor1, tensor2, tensor3
565 : TYPE(torch_tensor_type), INTENT(INOUT) :: grad1, grad2, grad3
566 :
567 : #if defined(__LIBTORCH)
568 : INTERFACE
569 : SUBROUTINE torch_c_tensor_grad_batch3(tensor1, tensor2, tensor3, grad1, grad2, grad3) &
570 : BIND(C, name="torch_c_tensor_grad_batch3")
571 : IMPORT :: C_PTR
572 : TYPE(C_PTR), VALUE :: tensor1, tensor2, tensor3
573 : TYPE(C_PTR) :: grad1, grad2, grad3
574 : END SUBROUTINE torch_c_tensor_grad_batch3
575 : END INTERFACE
576 :
577 338 : CPASSERT(C_ASSOCIATED(tensor1%c_ptr))
578 338 : CPASSERT(C_ASSOCIATED(tensor2%c_ptr))
579 338 : CPASSERT(C_ASSOCIATED(tensor3%c_ptr))
580 338 : CPASSERT(.NOT. C_ASSOCIATED(grad1%c_ptr))
581 338 : CPASSERT(.NOT. C_ASSOCIATED(grad2%c_ptr))
582 338 : CPASSERT(.NOT. C_ASSOCIATED(grad3%c_ptr))
583 : CALL torch_c_tensor_grad_batch3(tensor1=tensor1%c_ptr, tensor2=tensor2%c_ptr, &
584 : tensor3=tensor3%c_ptr, grad1=grad1%c_ptr, &
585 338 : grad2=grad2%c_ptr, grad3=grad3%c_ptr)
586 338 : CPASSERT(C_ASSOCIATED(grad1%c_ptr))
587 338 : CPASSERT(C_ASSOCIATED(grad2%c_ptr))
588 338 : CPASSERT(C_ASSOCIATED(grad3%c_ptr))
589 : #else
590 : CPABORT("CP2K compiled without the Torch library.")
591 : MARK_USED(tensor1)
592 : MARK_USED(tensor2)
593 : MARK_USED(tensor3)
594 : MARK_USED(grad1)
595 : MARK_USED(grad2)
596 : MARK_USED(grad3)
597 : #endif
598 338 : END SUBROUTINE torch_tensor_grad_batch3
599 :
600 : ! **************************************************************************************************
601 : !> \brief Returns the weighted sum of two Torch tensors.
602 : ! **************************************************************************************************
603 342 : SUBROUTINE torch_tensor_weighted_sum(values, weights, result)
604 : TYPE(torch_tensor_type), INTENT(IN) :: values, weights
605 : TYPE(torch_tensor_type), INTENT(INOUT) :: result
606 :
607 : #if defined(__LIBTORCH)
608 : INTERFACE
609 : SUBROUTINE torch_c_tensor_weighted_sum(values, weights, result) &
610 : BIND(C, name="torch_c_tensor_weighted_sum")
611 : IMPORT :: C_PTR
612 : TYPE(C_PTR), VALUE :: values
613 : TYPE(C_PTR), VALUE :: weights
614 : TYPE(C_PTR) :: result
615 : END SUBROUTINE torch_c_tensor_weighted_sum
616 : END INTERFACE
617 :
618 342 : CPASSERT(C_ASSOCIATED(values%c_ptr))
619 342 : CPASSERT(C_ASSOCIATED(weights%c_ptr))
620 342 : CPASSERT(.NOT. C_ASSOCIATED(result%c_ptr))
621 342 : CALL torch_c_tensor_weighted_sum(values=values%c_ptr, weights=weights%c_ptr, result=result%c_ptr)
622 342 : CPASSERT(C_ASSOCIATED(result%c_ptr))
623 : #else
624 : CPABORT("CP2K compiled without the Torch library.")
625 : MARK_USED(values)
626 : MARK_USED(weights)
627 : MARK_USED(result)
628 : #endif
629 342 : END SUBROUTINE torch_tensor_weighted_sum
630 :
631 : ! **************************************************************************************************
632 : !> \brief Returns a scalar double value from a Torch tensor.
633 : ! **************************************************************************************************
634 342 : FUNCTION torch_tensor_item_double(tensor) RESULT(value)
635 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
636 : REAL(KIND=dp) :: value
637 :
638 : #if defined(__LIBTORCH)
639 : INTERFACE
640 : FUNCTION torch_c_tensor_item_double(tensor) RESULT(value) &
641 : BIND(C, name="torch_c_tensor_item_double")
642 : IMPORT :: C_DOUBLE, C_PTR
643 : TYPE(C_PTR), VALUE :: tensor
644 : REAL(KIND=C_DOUBLE) :: value
645 : END FUNCTION torch_c_tensor_item_double
646 : END INTERFACE
647 :
648 342 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
649 342 : value = torch_c_tensor_item_double(tensor=tensor%c_ptr)
650 : #else
651 : value = 0.0_dp
652 : CPABORT("CP2K compiled without the Torch library.")
653 : MARK_USED(tensor)
654 : #endif
655 342 : END FUNCTION torch_tensor_item_double
656 :
657 : ! **************************************************************************************************
658 : !> \brief Releases a Torch tensor and all its ressources.
659 : !> \author Ole Schuett
660 : ! **************************************************************************************************
661 6892 : SUBROUTINE torch_tensor_release(tensor)
662 : TYPE(torch_tensor_type), INTENT(INOUT) :: tensor
663 :
664 : #if defined(__LIBTORCH)
665 : INTERFACE
666 : SUBROUTINE torch_c_tensor_release(tensor) BIND(C, name="torch_c_tensor_release")
667 : IMPORT :: C_PTR
668 : TYPE(C_PTR), VALUE :: tensor
669 : END SUBROUTINE torch_c_tensor_release
670 : END INTERFACE
671 :
672 6892 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
673 6892 : CALL torch_c_tensor_release(tensor=tensor%c_ptr)
674 6892 : tensor%c_ptr = C_NULL_PTR
675 : #else
676 : CPABORT("CP2K was compiled without Torch library.")
677 : MARK_USED(tensor)
678 : #endif
679 6892 : END SUBROUTINE torch_tensor_release
680 :
681 : ! **************************************************************************************************
682 : !> \brief Creates an empty Torch dictionary.
683 : !> \author Ole Schuett
684 : ! **************************************************************************************************
685 416 : SUBROUTINE torch_dict_create(dict)
686 : TYPE(torch_dict_type), INTENT(INOUT) :: dict
687 :
688 : #if defined(__LIBTORCH)
689 : INTERFACE
690 : SUBROUTINE torch_c_dict_create(dict) BIND(C, name="torch_c_dict_create")
691 : IMPORT :: C_PTR
692 : TYPE(C_PTR) :: dict
693 : END SUBROUTINE torch_c_dict_create
694 : END INTERFACE
695 :
696 416 : CPASSERT(.NOT. C_ASSOCIATED(dict%c_ptr))
697 416 : CALL torch_c_dict_create(dict=dict%c_ptr)
698 416 : CPASSERT(C_ASSOCIATED(dict%c_ptr))
699 : #else
700 : CPABORT("CP2K was compiled without Torch library.")
701 : MARK_USED(dict)
702 : #endif
703 416 : END SUBROUTINE torch_dict_create
704 :
705 : ! **************************************************************************************************
706 : !> \brief Clones a Torch dictionary.
707 : ! **************************************************************************************************
708 38 : SUBROUTINE torch_dict_clone(source, target)
709 : TYPE(torch_dict_type), INTENT(IN) :: source
710 : TYPE(torch_dict_type), INTENT(INOUT) :: target
711 :
712 : #if defined(__LIBTORCH)
713 : INTERFACE
714 : SUBROUTINE torch_c_dict_clone(source, target) BIND(C, name="torch_c_dict_clone")
715 : IMPORT :: C_PTR
716 : TYPE(C_PTR), VALUE :: source
717 : TYPE(C_PTR) :: target
718 : END SUBROUTINE torch_c_dict_clone
719 : END INTERFACE
720 :
721 38 : CPASSERT(C_ASSOCIATED(source%c_ptr))
722 38 : CPASSERT(.NOT. C_ASSOCIATED(target%c_ptr))
723 38 : CALL torch_c_dict_clone(source=source%c_ptr, target=target%c_ptr)
724 38 : CPASSERT(C_ASSOCIATED(target%c_ptr))
725 : #else
726 : CPABORT("CP2K was compiled without Torch library.")
727 : MARK_USED(source)
728 : MARK_USED(target)
729 : #endif
730 38 : END SUBROUTINE torch_dict_clone
731 :
732 : ! **************************************************************************************************
733 : !> \brief Inserts a Torch tensor into a Torch dictionary.
734 : !> \author Ole Schuett
735 : ! **************************************************************************************************
736 2860 : SUBROUTINE torch_dict_insert(dict, key, tensor)
737 : TYPE(torch_dict_type), INTENT(INOUT) :: dict
738 : CHARACTER(len=*), INTENT(IN) :: key
739 : TYPE(torch_tensor_type), INTENT(IN) :: tensor
740 :
741 : #if defined(__LIBTORCH)
742 :
743 : INTERFACE
744 : SUBROUTINE torch_c_dict_insert(dict, key, tensor) &
745 : BIND(C, name="torch_c_dict_insert")
746 : IMPORT :: C_CHAR, C_PTR
747 : TYPE(C_PTR), VALUE :: dict
748 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: key
749 : TYPE(C_PTR), VALUE :: tensor
750 : END SUBROUTINE torch_c_dict_insert
751 : END INTERFACE
752 :
753 2860 : CPASSERT(C_ASSOCIATED(dict%c_ptr))
754 2860 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
755 2860 : CALL torch_c_dict_insert(dict=dict%c_ptr, key=TRIM(key)//C_NULL_CHAR, tensor=tensor%c_ptr)
756 : #else
757 : CPABORT("CP2K compiled without the Torch library.")
758 : MARK_USED(dict)
759 : MARK_USED(key)
760 : MARK_USED(tensor)
761 : #endif
762 2860 : END SUBROUTINE torch_dict_insert
763 :
764 : ! **************************************************************************************************
765 : !> \brief Retrieves a Torch tensor from a Torch dictionary.
766 : !> \author Ole Schuett
767 : ! **************************************************************************************************
768 76 : SUBROUTINE torch_dict_get(dict, key, tensor)
769 : TYPE(torch_dict_type), INTENT(IN) :: dict
770 : CHARACTER(len=*), INTENT(IN) :: key
771 : TYPE(torch_tensor_type), INTENT(INOUT) :: tensor
772 :
773 : #if defined(__LIBTORCH)
774 :
775 : INTERFACE
776 : SUBROUTINE torch_c_dict_get(dict, key, tensor) &
777 : BIND(C, name="torch_c_dict_get")
778 : IMPORT :: C_CHAR, C_PTR
779 : TYPE(C_PTR), VALUE :: dict
780 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: key
781 : TYPE(C_PTR) :: tensor
782 : END SUBROUTINE torch_c_dict_get
783 : END INTERFACE
784 :
785 76 : CPASSERT(C_ASSOCIATED(dict%c_ptr))
786 76 : CPASSERT(.NOT. C_ASSOCIATED(tensor%c_ptr))
787 76 : CALL torch_c_dict_get(dict=dict%c_ptr, key=TRIM(key)//C_NULL_CHAR, tensor=tensor%c_ptr)
788 76 : CPASSERT(C_ASSOCIATED(tensor%c_ptr))
789 :
790 : #else
791 : CPABORT("CP2K compiled without the Torch library.")
792 : MARK_USED(dict)
793 : MARK_USED(key)
794 : MARK_USED(tensor)
795 : #endif
796 76 : END SUBROUTINE torch_dict_get
797 :
798 : ! **************************************************************************************************
799 : !> \brief Releases a Torch dictionary and all its ressources.
800 : !> \author Ole Schuett
801 : ! **************************************************************************************************
802 454 : SUBROUTINE torch_dict_release(dict)
803 : TYPE(torch_dict_type), INTENT(INOUT) :: dict
804 :
805 : #if defined(__LIBTORCH)
806 : INTERFACE
807 : SUBROUTINE torch_c_dict_release(dict) BIND(C, name="torch_c_dict_release")
808 : IMPORT :: C_PTR
809 : TYPE(C_PTR), VALUE :: dict
810 : END SUBROUTINE torch_c_dict_release
811 : END INTERFACE
812 :
813 454 : CPASSERT(C_ASSOCIATED(dict%c_ptr))
814 454 : CALL torch_c_dict_release(dict=dict%c_ptr)
815 454 : dict%c_ptr = C_NULL_PTR
816 : #else
817 : CPABORT("CP2K was compiled without Torch library.")
818 : MARK_USED(dict)
819 : #endif
820 454 : END SUBROUTINE torch_dict_release
821 :
822 : ! **************************************************************************************************
823 : !> \brief Loads a Torch model from given "*.pth" file. (In Torch lingo models are called modules)
824 : !> \author Ole Schuett
825 : ! **************************************************************************************************
826 16 : SUBROUTINE torch_model_load(model, filename)
827 : TYPE(torch_model_type), INTENT(INOUT) :: model
828 : CHARACTER(len=*), INTENT(IN) :: filename
829 :
830 : #if defined(__LIBTORCH)
831 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_load'
832 : INTEGER :: handle
833 :
834 : INTERFACE
835 : SUBROUTINE torch_c_model_load(model, filename) BIND(C, name="torch_c_model_load")
836 : IMPORT :: C_PTR, C_CHAR
837 : TYPE(C_PTR) :: model
838 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: filename
839 : END SUBROUTINE torch_c_model_load
840 : END INTERFACE
841 :
842 16 : CALL timeset(routineN, handle)
843 16 : CPASSERT(.NOT. C_ASSOCIATED(model%c_ptr))
844 16 : CALL torch_c_model_load(model=model%c_ptr, filename=TRIM(filename)//C_NULL_CHAR)
845 16 : CPASSERT(C_ASSOCIATED(model%c_ptr))
846 16 : CALL timestop(handle)
847 : #else
848 : CPABORT("CP2K was compiled without Torch library.")
849 : MARK_USED(model)
850 : MARK_USED(filename)
851 : #endif
852 16 : END SUBROUTINE torch_model_load
853 :
854 : ! **************************************************************************************************
855 : !> \brief Loads a Torch model and reads two metadata entries in the same archive pass.
856 : ! **************************************************************************************************
857 19 : SUBROUTINE torch_model_load_with_metadata(model, filename, key1, value1, key2, value2)
858 : TYPE(torch_model_type), INTENT(INOUT) :: model
859 : CHARACTER(len=*), INTENT(IN) :: filename, key1, key2
860 : CHARACTER(:), ALLOCATABLE, INTENT(OUT) :: value1, value2
861 :
862 : #if defined(__LIBTORCH)
863 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_load_with_metadata'
864 : INTEGER :: handle, length1, length2
865 : TYPE(C_PTR) :: content1_c, content2_c
866 :
867 : INTERFACE
868 : SUBROUTINE torch_c_model_load_with_metadata(model, filename, key1, key2, &
869 : content1, length1, content2, length2) &
870 : BIND(C, name="torch_c_model_load_with_metadata")
871 : IMPORT :: C_CHAR, C_INT, C_PTR
872 : TYPE(C_PTR) :: model
873 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: filename, key1, key2
874 : TYPE(C_PTR) :: content1, content2
875 : INTEGER(kind=C_INT) :: length1, length2
876 : END SUBROUTINE torch_c_model_load_with_metadata
877 : END INTERFACE
878 :
879 19 : CALL timeset(routineN, handle)
880 19 : CPASSERT(.NOT. C_ASSOCIATED(model%c_ptr))
881 19 : content1_c = C_NULL_PTR
882 19 : content2_c = C_NULL_PTR
883 19 : length1 = -1
884 19 : length2 = -1
885 : CALL torch_c_model_load_with_metadata(model=model%c_ptr, &
886 : filename=TRIM(filename)//C_NULL_CHAR, &
887 : key1=TRIM(key1)//C_NULL_CHAR, &
888 : key2=TRIM(key2)//C_NULL_CHAR, &
889 : content1=content1_c, length1=length1, &
890 19 : content2=content2_c, length2=length2)
891 19 : CPASSERT(C_ASSOCIATED(model%c_ptr))
892 19 : CALL c_string_to_allocatable(content1_c, length1, value1)
893 19 : CALL c_string_to_allocatable(content2_c, length2, value2)
894 19 : CALL timestop(handle)
895 : #else
896 : CPABORT("CP2K was compiled without Torch library.")
897 : MARK_USED(model)
898 : MARK_USED(filename)
899 : MARK_USED(key1)
900 : MARK_USED(value1)
901 : MARK_USED(key2)
902 : MARK_USED(value2)
903 : #endif
904 19 : END SUBROUTINE torch_model_load_with_metadata
905 :
906 : ! **************************************************************************************************
907 : !> \brief Maps serialized TorchScript device constants to the active Torch device.
908 : ! **************************************************************************************************
909 27 : SUBROUTINE torch_model_remap_device_constants(model)
910 : TYPE(torch_model_type), INTENT(INOUT) :: model
911 :
912 : #if defined(__LIBTORCH)
913 : INTERFACE
914 : SUBROUTINE torch_c_model_remap_device_constants(model) &
915 : BIND(C, name="torch_c_model_remap_device_constants")
916 : IMPORT :: C_PTR
917 : TYPE(C_PTR), VALUE :: model
918 : END SUBROUTINE torch_c_model_remap_device_constants
919 : END INTERFACE
920 :
921 27 : CPASSERT(C_ASSOCIATED(model%c_ptr))
922 27 : CALL torch_c_model_remap_device_constants(model=model%c_ptr)
923 : #else
924 : CPABORT("CP2K was compiled without Torch library.")
925 : MARK_USED(model)
926 : #endif
927 27 : END SUBROUTINE torch_model_remap_device_constants
928 :
929 : ! **************************************************************************************************
930 : !> \brief Prepare a model for higher input derivatives.
931 : ! **************************************************************************************************
932 2 : SUBROUTINE torch_model_prepare_higher_derivatives(model)
933 : TYPE(torch_model_type), INTENT(INOUT) :: model
934 :
935 : #if defined(__LIBTORCH)
936 : INTERFACE
937 : SUBROUTINE torch_c_model_prepare_higher_derivatives(model) &
938 : BIND(C, name="torch_c_model_prepare_higher_derivatives")
939 : IMPORT :: C_PTR
940 : TYPE(C_PTR), VALUE :: model
941 : END SUBROUTINE torch_c_model_prepare_higher_derivatives
942 : END INTERFACE
943 :
944 2 : CPASSERT(C_ASSOCIATED(model%c_ptr))
945 2 : CALL torch_c_model_prepare_higher_derivatives(model=model%c_ptr)
946 : #else
947 : CPABORT("CP2K was compiled without Torch library.")
948 : MARK_USED(model)
949 : #endif
950 2 : END SUBROUTINE torch_model_prepare_higher_derivatives
951 :
952 : ! **************************************************************************************************
953 : !> \brief Promote float32 model state and explicit floating-point casts to double precision.
954 : ! **************************************************************************************************
955 17 : SUBROUTINE torch_model_promote_float32(model)
956 : TYPE(torch_model_type), INTENT(INOUT) :: model
957 :
958 : #if defined(__LIBTORCH)
959 : INTERFACE
960 : SUBROUTINE torch_c_model_promote_float32(model) BIND(C, name="torch_c_model_promote_float32")
961 : IMPORT :: C_PTR
962 : TYPE(C_PTR), VALUE :: model
963 : END SUBROUTINE torch_c_model_promote_float32
964 : END INTERFACE
965 :
966 17 : CPASSERT(C_ASSOCIATED(model%c_ptr))
967 17 : CALL torch_c_model_promote_float32(model%c_ptr)
968 : #else
969 : CPABORT("CP2K was compiled without Torch library.")
970 : MARK_USED(model)
971 : #endif
972 17 : END SUBROUTINE torch_model_promote_float32
973 :
974 : ! **************************************************************************************************
975 : !> \brief Disable gradients for inference-only model parameters.
976 : ! **************************************************************************************************
977 19 : SUBROUTINE torch_model_disable_parameter_gradients(model)
978 : TYPE(torch_model_type), INTENT(INOUT) :: model
979 :
980 : #if defined(__LIBTORCH)
981 : INTERFACE
982 : SUBROUTINE torch_c_model_disable_parameter_gradients(model) &
983 : BIND(C, name="torch_c_model_disable_parameter_gradients")
984 : IMPORT :: C_PTR
985 : TYPE(C_PTR), VALUE :: model
986 : END SUBROUTINE torch_c_model_disable_parameter_gradients
987 : END INTERFACE
988 :
989 19 : CPASSERT(C_ASSOCIATED(model%c_ptr))
990 19 : CALL torch_c_model_disable_parameter_gradients(model=model%c_ptr)
991 : #else
992 : CPABORT("CP2K was compiled without Torch library.")
993 : MARK_USED(model)
994 : #endif
995 19 : END SUBROUTINE torch_model_disable_parameter_gradients
996 :
997 : ! **************************************************************************************************
998 : !> \brief Evaluates the given Torch model.
999 : !> \author Ole Schuett
1000 : ! **************************************************************************************************
1001 62 : SUBROUTINE torch_model_forward(model, inputs, outputs)
1002 : TYPE(torch_model_type), INTENT(INOUT) :: model
1003 : TYPE(torch_dict_type), INTENT(IN) :: inputs
1004 : TYPE(torch_dict_type), INTENT(INOUT) :: outputs
1005 :
1006 : #if defined(__LIBTORCH)
1007 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_forward'
1008 : INTEGER :: handle
1009 :
1010 : INTERFACE
1011 : SUBROUTINE torch_c_model_forward(model, inputs, outputs) BIND(C, name="torch_c_model_forward")
1012 : IMPORT :: C_PTR
1013 : TYPE(C_PTR), VALUE :: model
1014 : TYPE(C_PTR), VALUE :: inputs
1015 : TYPE(C_PTR), VALUE :: outputs
1016 : END SUBROUTINE torch_c_model_forward
1017 : END INTERFACE
1018 :
1019 62 : CALL timeset(routineN, handle)
1020 62 : CPASSERT(C_ASSOCIATED(model%c_ptr))
1021 62 : CPASSERT(C_ASSOCIATED(inputs%c_ptr))
1022 62 : CPASSERT(C_ASSOCIATED(outputs%c_ptr))
1023 62 : CALL torch_c_model_forward(model=model%c_ptr, inputs=inputs%c_ptr, outputs=outputs%c_ptr)
1024 62 : CALL timestop(handle)
1025 : #else
1026 : CPABORT("CP2K was compiled without Torch library.")
1027 : MARK_USED(model)
1028 : MARK_USED(inputs)
1029 : MARK_USED(outputs)
1030 : #endif
1031 62 : END SUBROUTINE torch_model_forward
1032 :
1033 : ! **************************************************************************************************
1034 : !> \brief Evaluates a TorchScript model method expecting keyword argument "mol".
1035 : ! **************************************************************************************************
1036 342 : SUBROUTINE torch_model_forward_mol_tensor(model, method_name, inputs, output)
1037 : TYPE(torch_model_type), INTENT(INOUT) :: model
1038 : CHARACTER(len=*), INTENT(IN) :: method_name
1039 : TYPE(torch_dict_type), INTENT(IN) :: inputs
1040 : TYPE(torch_tensor_type), INTENT(INOUT) :: output
1041 :
1042 : #if defined(__LIBTORCH)
1043 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_forward_mol_tensor'
1044 : INTEGER :: handle
1045 :
1046 : INTERFACE
1047 : SUBROUTINE torch_c_model_forward_mol_tensor(model, method_name, inputs, output) &
1048 : BIND(C, name="torch_c_model_forward_mol_tensor")
1049 : IMPORT :: C_CHAR, C_PTR
1050 : TYPE(C_PTR), VALUE :: model
1051 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: method_name
1052 : TYPE(C_PTR), VALUE :: inputs
1053 : TYPE(C_PTR) :: output
1054 : END SUBROUTINE torch_c_model_forward_mol_tensor
1055 : END INTERFACE
1056 :
1057 342 : CALL timeset(routineN, handle)
1058 342 : CPASSERT(C_ASSOCIATED(model%c_ptr))
1059 342 : CPASSERT(C_ASSOCIATED(inputs%c_ptr))
1060 342 : CPASSERT(.NOT. C_ASSOCIATED(output%c_ptr))
1061 : CALL torch_c_model_forward_mol_tensor(model=model%c_ptr, &
1062 : method_name=TRIM(method_name)//C_NULL_CHAR, &
1063 : inputs=inputs%c_ptr, &
1064 342 : output=output%c_ptr)
1065 342 : CPASSERT(C_ASSOCIATED(output%c_ptr))
1066 342 : CALL timestop(handle)
1067 : #else
1068 : CPABORT("CP2K was compiled without Torch library.")
1069 : MARK_USED(model)
1070 : MARK_USED(method_name)
1071 : MARK_USED(inputs)
1072 : MARK_USED(output)
1073 : #endif
1074 342 : END SUBROUTINE torch_model_forward_mol_tensor
1075 :
1076 : ! **************************************************************************************************
1077 : !> \brief Releases a Torch model and all its ressources.
1078 : !> \author Ole Schuett
1079 : ! **************************************************************************************************
1080 35 : SUBROUTINE torch_model_release(model)
1081 : TYPE(torch_model_type), INTENT(INOUT) :: model
1082 :
1083 : #if defined(__LIBTORCH)
1084 : INTERFACE
1085 : SUBROUTINE torch_c_model_release(model) BIND(C, name="torch_c_model_release")
1086 : IMPORT :: C_PTR
1087 : TYPE(C_PTR), VALUE :: model
1088 : END SUBROUTINE torch_c_model_release
1089 : END INTERFACE
1090 :
1091 35 : CPASSERT(C_ASSOCIATED(model%c_ptr))
1092 35 : CALL torch_c_model_release(model=model%c_ptr)
1093 35 : model%c_ptr = C_NULL_PTR
1094 : #else
1095 : CPABORT("CP2K was compiled without Torch library.")
1096 : MARK_USED(model)
1097 : #endif
1098 35 : END SUBROUTINE torch_model_release
1099 :
1100 : ! **************************************************************************************************
1101 : !> \brief Reads metadata entry from given "*.pth" file. (In Torch lingo they are called extra files)
1102 : !> \author Ole Schuett
1103 : ! **************************************************************************************************
1104 40 : FUNCTION torch_model_read_metadata(filename, key) RESULT(res)
1105 : CHARACTER(len=*), INTENT(IN) :: filename, key
1106 : CHARACTER(:), ALLOCATABLE :: res
1107 :
1108 : #if defined(__LIBTORCH)
1109 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_read_metadata'
1110 : INTEGER :: handle
1111 :
1112 : INTEGER :: length
1113 : TYPE(C_PTR) :: content_c
1114 :
1115 : INTERFACE
1116 : SUBROUTINE torch_c_model_read_metadata(filename, key, content, length) &
1117 : BIND(C, name="torch_c_model_read_metadata")
1118 : IMPORT :: C_CHAR, C_PTR, C_INT
1119 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: filename, key
1120 : TYPE(C_PTR) :: content
1121 : INTEGER(kind=C_INT) :: length
1122 : END SUBROUTINE torch_c_model_read_metadata
1123 : END INTERFACE
1124 :
1125 40 : CALL timeset(routineN, handle)
1126 40 : content_c = C_NULL_PTR
1127 40 : length = -1
1128 : CALL torch_c_model_read_metadata(filename=TRIM(filename)//C_NULL_CHAR, &
1129 : key=TRIM(key)//C_NULL_CHAR, &
1130 : content=content_c, &
1131 40 : length=length)
1132 40 : CALL c_string_to_allocatable(content_c, length, res)
1133 40 : CALL timestop(handle)
1134 : #else
1135 : res = ""
1136 : MARK_USED(filename)
1137 : MARK_USED(key)
1138 : CPABORT("CP2K was compiled without Torch library.")
1139 : #endif
1140 40 : END FUNCTION torch_model_read_metadata
1141 :
1142 : ! **************************************************************************************************
1143 : !> \brief Move a C-allocated null-terminated string into an allocatable Fortran string.
1144 : ! **************************************************************************************************
1145 78 : SUBROUTINE c_string_to_allocatable(content_c, length, res)
1146 : TYPE(C_PTR), INTENT(INOUT) :: content_c
1147 : INTEGER, INTENT(IN) :: length
1148 : CHARACTER(:), ALLOCATABLE, INTENT(OUT) :: res
1149 :
1150 : #if defined(__LIBTORCH)
1151 : CHARACTER(LEN=1, KIND=C_CHAR), DIMENSION(:), &
1152 78 : POINTER :: content_f
1153 : INTEGER :: i
1154 :
1155 : INTERFACE
1156 : SUBROUTINE torch_c_free_string(content) BIND(C, name="torch_c_free_string")
1157 : IMPORT :: C_PTR
1158 : TYPE(C_PTR), VALUE :: content
1159 : END SUBROUTINE torch_c_free_string
1160 : END INTERFACE
1161 :
1162 0 : CPASSERT(C_ASSOCIATED(content_c))
1163 78 : CPASSERT(length >= 0)
1164 :
1165 156 : CALL C_F_POINTER(content_c, content_f, shape=[length + 1])
1166 78 : CPASSERT(content_f(length + 1) == C_NULL_CHAR)
1167 :
1168 78 : ALLOCATE (CHARACTER(LEN=length) :: res)
1169 3278 : DO i = 1, length
1170 3200 : CPASSERT(content_f(i) /= C_NULL_CHAR)
1171 3278 : res(i:i) = content_f(i)
1172 : END DO
1173 :
1174 78 : NULLIFY (content_f)
1175 78 : CALL torch_c_free_string(content_c)
1176 78 : content_c = C_NULL_PTR
1177 :
1178 : #else
1179 : res = ""
1180 : MARK_USED(content_c)
1181 : MARK_USED(length)
1182 : CPABORT("CP2K was compiled without Torch library.")
1183 : #endif
1184 78 : END SUBROUTINE c_string_to_allocatable
1185 :
1186 : ! **************************************************************************************************
1187 : !> \brief Returns true iff the Torch CUDA backend is available.
1188 : !> \author Ole Schuett
1189 : ! **************************************************************************************************
1190 2 : FUNCTION torch_cuda_is_available() RESULT(res)
1191 : LOGICAL :: res
1192 :
1193 : #if defined(__LIBTORCH)
1194 : INTERFACE
1195 : FUNCTION torch_c_cuda_is_available() BIND(C, name="torch_c_cuda_is_available")
1196 : IMPORT :: C_BOOL
1197 : LOGICAL(C_BOOL) :: torch_c_cuda_is_available
1198 : END FUNCTION torch_c_cuda_is_available
1199 : END INTERFACE
1200 :
1201 2 : res = torch_c_cuda_is_available()
1202 : #else
1203 : CPABORT("CP2K was compiled without Torch library.")
1204 : res = .FALSE.
1205 : #endif
1206 2 : END FUNCTION torch_cuda_is_available
1207 :
1208 : ! **************************************************************************************************
1209 : !> \brief Return the number of CUDA devices visible to Torch.
1210 : ! **************************************************************************************************
1211 0 : FUNCTION torch_cuda_device_count() RESULT(count)
1212 : INTEGER :: count
1213 :
1214 : #if defined(__LIBTORCH)
1215 : INTERFACE
1216 : FUNCTION torch_c_cuda_device_count() BIND(C, name="torch_c_cuda_device_count")
1217 : IMPORT :: C_INT
1218 : INTEGER(C_INT) :: torch_c_cuda_device_count
1219 : END FUNCTION torch_c_cuda_device_count
1220 : END INTERFACE
1221 :
1222 0 : count = torch_c_cuda_device_count()
1223 : #else
1224 : CPABORT("CP2K was compiled without Torch library.")
1225 : count = 0
1226 : #endif
1227 0 : END FUNCTION torch_cuda_device_count
1228 :
1229 : ! **************************************************************************************************
1230 : !> \brief Set whether to allow the use of TF32.
1231 : !> Needed due to changes in defaults from pytorch 1.7 to 1.11 to >=1.12
1232 : !> See https://pytorch.org/docs/stable/notes/cuda.html
1233 : !> \author Gabriele Tocci
1234 : ! **************************************************************************************************
1235 6 : SUBROUTINE torch_allow_tf32(allow_tf32)
1236 : LOGICAL, INTENT(IN) :: allow_tf32
1237 :
1238 : #if defined(__LIBTORCH)
1239 : INTERFACE
1240 : SUBROUTINE torch_c_allow_tf32(allow_tf32) BIND(C, name="torch_c_allow_tf32")
1241 : IMPORT :: C_BOOL
1242 : LOGICAL(C_BOOL), VALUE :: allow_tf32
1243 : END SUBROUTINE torch_c_allow_tf32
1244 : END INTERFACE
1245 :
1246 6 : CALL torch_c_allow_tf32(allow_tf32=LOGICAL(allow_tf32, C_BOOL))
1247 : #else
1248 : CPABORT("CP2K was compiled without Torch library.")
1249 : MARK_USED(allow_tf32)
1250 : #endif
1251 6 : END SUBROUTINE torch_allow_tf32
1252 :
1253 : ! **************************************************************************************************
1254 : !> \brief Freeze the given Torch model: applies generic optimization that speed up model.
1255 : !> See https://pytorch.org/docs/stable/generated/torch.jit.freeze.html
1256 : !> \author Gabriele Tocci
1257 : ! **************************************************************************************************
1258 6 : SUBROUTINE torch_model_freeze(model)
1259 : TYPE(torch_model_type), INTENT(INOUT) :: model
1260 :
1261 : #if defined(__LIBTORCH)
1262 : CHARACTER(len=*), PARAMETER :: routineN = 'torch_model_freeze'
1263 : INTEGER :: handle
1264 :
1265 : INTERFACE
1266 : SUBROUTINE torch_c_model_freeze(model) BIND(C, name="torch_c_model_freeze")
1267 : IMPORT :: C_PTR
1268 : TYPE(C_PTR), VALUE :: model
1269 : END SUBROUTINE torch_c_model_freeze
1270 : END INTERFACE
1271 :
1272 6 : CALL timeset(routineN, handle)
1273 6 : CPASSERT(C_ASSOCIATED(model%c_ptr))
1274 6 : CALL torch_c_model_freeze(model=model%c_ptr)
1275 6 : CALL timestop(handle)
1276 : #else
1277 : CPABORT("CP2K was compiled without Torch library.")
1278 : MARK_USED(model)
1279 : #endif
1280 6 : END SUBROUTINE torch_model_freeze
1281 :
1282 : ! **************************************************************************************************
1283 : !> \brief Freeze a Torch model while preserving one exported method.
1284 : !> \param model ...
1285 : !> \param method_name ...
1286 : ! **************************************************************************************************
1287 19 : SUBROUTINE torch_model_freeze_preserving_method(model, method_name)
1288 : TYPE(torch_model_type), INTENT(INOUT) :: model
1289 : CHARACTER(len=*), INTENT(IN) :: method_name
1290 :
1291 : #if defined(__LIBTORCH)
1292 : CHARACTER(len=*), PARAMETER :: routineN = &
1293 : 'torch_model_freeze_preserving_method'
1294 : INTEGER :: handle
1295 :
1296 : INTERFACE
1297 : SUBROUTINE torch_c_model_freeze_preserving_method(model, method_name) &
1298 : BIND(C, name="torch_c_model_freeze_preserving_method")
1299 : IMPORT :: C_CHAR, C_PTR
1300 : TYPE(C_PTR), VALUE :: model
1301 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: method_name
1302 : END SUBROUTINE torch_c_model_freeze_preserving_method
1303 : END INTERFACE
1304 :
1305 19 : CALL timeset(routineN, handle)
1306 19 : CPASSERT(C_ASSOCIATED(model%c_ptr))
1307 : CALL torch_c_model_freeze_preserving_method( &
1308 19 : model=model%c_ptr, method_name=TRIM(method_name)//C_NULL_CHAR)
1309 19 : CALL timestop(handle)
1310 : #else
1311 : CPABORT("CP2K was compiled without Torch library.")
1312 : MARK_USED(method_name)
1313 : MARK_USED(model)
1314 : #endif
1315 19 : END SUBROUTINE torch_model_freeze_preserving_method
1316 :
1317 : #:set typenames = ['int64', 'double', 'string']
1318 : #:set types_f = ['INTEGER(kind=int_8)', 'REAL(dp)', 'CHARACTER(LEN=default_string_length)']
1319 : #:set types_c = ['INTEGER(kind=C_INT64_T)', 'REAL(kind=C_DOUBLE)', 'CHARACTER(kind=C_CHAR), DIMENSION(*)']
1320 : #:set zeros_f = ['0', '0.0_dp', '""']
1321 :
1322 : #:for typename, type_f, type_c, zero_f in zip(typenames, types_f, types_c, zeros_f)
1323 : ! **************************************************************************************************
1324 : !> \brief Retrieves an attribute from a Torch model. Must be called before torch_model_freeze.
1325 : !> \author Ole Schuett
1326 : ! **************************************************************************************************
1327 64 : SUBROUTINE torch_model_get_attr_${typename}$ (model, key, dest)
1328 : TYPE(torch_model_type), INTENT(IN) :: model
1329 : CHARACTER(len=*), INTENT(IN) :: key
1330 : ${type_f}$, INTENT(OUT) :: dest
1331 :
1332 : #if defined(__LIBTORCH)
1333 :
1334 : INTERFACE
1335 : SUBROUTINE torch_c_model_get_attr_${typename}$ (model, key, dest) &
1336 : BIND(C, name="torch_c_model_get_attr_${typename}$")
1337 : IMPORT :: C_PTR, C_CHAR, C_INT64_T, C_DOUBLE
1338 : TYPE(C_PTR), VALUE :: model
1339 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: key
1340 : ${type_c}$ :: dest
1341 : END SUBROUTINE torch_c_model_get_attr_${typename}$
1342 : END INTERFACE
1343 :
1344 : CALL torch_c_model_get_attr_${typename}$ (model=model%c_ptr, &
1345 : key=TRIM(key)//C_NULL_CHAR, &
1346 64 : dest=dest)
1347 : #else
1348 : dest = ${zero_f}$
1349 : MARK_USED(model)
1350 : MARK_USED(key)
1351 : CPABORT("CP2K compiled without the Torch library.")
1352 : #endif
1353 : END SUBROUTINE torch_model_get_attr_${typename}$
1354 64 : #:endfor
1355 :
1356 : ! **************************************************************************************************
1357 : !> \brief Retrieves an attribute from a Torch model. Must be called before torch_model_freeze.
1358 : !> \author Ole Schuett
1359 : ! **************************************************************************************************
1360 40 : SUBROUTINE torch_model_get_attr_int32(model, key, dest)
1361 : TYPE(torch_model_type), INTENT(IN) :: model
1362 : CHARACTER(len=*), INTENT(IN) :: key
1363 : INTEGER, INTENT(OUT) :: dest
1364 :
1365 : INTEGER(kind=int_8) :: temp
1366 40 : CALL torch_model_get_attr_int64(model, key, temp)
1367 40 : CPASSERT(ABS(temp) < HUGE(dest))
1368 40 : dest = INT(temp)
1369 40 : END SUBROUTINE torch_model_get_attr_int32
1370 :
1371 : ! **************************************************************************************************
1372 : !> \brief Retrieves a list attribute from a Torch model. Must be called before torch_model_freeze.
1373 : !> \author Ole Schuett
1374 : ! **************************************************************************************************
1375 8 : SUBROUTINE torch_model_get_attr_strlist(model, key, dest)
1376 : TYPE(torch_model_type), INTENT(IN) :: model
1377 : CHARACTER(len=*), INTENT(IN) :: key
1378 : CHARACTER(LEN=default_string_length), &
1379 : ALLOCATABLE, DIMENSION(:) :: dest
1380 :
1381 : #if defined(__LIBTORCH)
1382 :
1383 : INTEGER :: num_items, i
1384 :
1385 : INTERFACE
1386 : SUBROUTINE torch_c_model_get_attr_list_size(model, key, size) &
1387 : BIND(C, name="torch_c_model_get_attr_list_size")
1388 : IMPORT :: C_PTR, C_CHAR, C_INT
1389 : TYPE(C_PTR), VALUE :: model
1390 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: key
1391 : INTEGER(kind=C_INT) :: size
1392 : END SUBROUTINE torch_c_model_get_attr_list_size
1393 : END INTERFACE
1394 :
1395 : INTERFACE
1396 : SUBROUTINE torch_c_model_get_attr_strlist(model, key, index, dest) &
1397 : BIND(C, name="torch_c_model_get_attr_strlist")
1398 : IMPORT :: C_PTR, C_CHAR, C_INT
1399 : TYPE(C_PTR), VALUE :: model
1400 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: key
1401 : INTEGER(kind=C_INT), VALUE :: index
1402 : CHARACTER(kind=C_CHAR), DIMENSION(*) :: dest
1403 : END SUBROUTINE torch_c_model_get_attr_strlist
1404 : END INTERFACE
1405 :
1406 : CALL torch_c_model_get_attr_list_size(model=model%c_ptr, &
1407 : key=TRIM(key)//C_NULL_CHAR, &
1408 8 : size=num_items)
1409 24 : ALLOCATE (dest(num_items))
1410 24 : dest(:) = ""
1411 :
1412 24 : DO i = 1, num_items
1413 : CALL torch_c_model_get_attr_strlist(model=model%c_ptr, &
1414 : key=TRIM(key)//C_NULL_CHAR, &
1415 : index=i - 1, &
1416 24 : dest=dest(i))
1417 :
1418 : END DO
1419 : #else
1420 : CPABORT("CP2K compiled without the Torch library.")
1421 : MARK_USED(model)
1422 : MARK_USED(key)
1423 : MARK_USED(dest)
1424 : #endif
1425 :
1426 8 : END SUBROUTINE torch_model_get_attr_strlist
1427 :
1428 0 : END MODULE torch_api
|