@@ -239,8 +239,10 @@ private void _toEpilog(ScalarType? dtype, Device device)
239239 . ToDictionary ( field => field . ComponentName ( ) ) ;
240240
241241 foreach ( var ( name , param ) in named_parameters ( false ) . ToList ( ) ) {
242+ using var grad = param . grad ;
243+
242244 if ( ! param . toWillCopy ( dtype ?? param . dtype , device ?? param . device ) &&
243- ( param . grad ( ) is null || ! param . grad ( ) . toWillCopy ( dtype ?? param . dtype , device ?? param . device ) ) )
245+ ( grad is null || ! grad . toWillCopy ( dtype ?? param . dtype , device ?? param . device ) ) )
244246 continue ;
245247
246248 Parameter p ;
@@ -252,20 +254,19 @@ private void _toEpilog(ScalarType? dtype, Device device)
252254 // disable grad we would need to call .detach() on the moved tensor.
253255 using ( var d = torch . no_grad ( ) ) {
254256 p = new Parameter (
255- param . to ( paramType , device ?? param . device ) . DetachFromDisposeScope ( ) , param . requires_grad )
256- . DetachFromDisposeScope ( ) as Parameter ;
257+ data : param . to ( paramType , device ?? param . device ) ,
258+ requires_grad : param . requires_grad ) ;
259+ _ = p . DetachFromDisposeScope ( ) ;
257260
258261 // Copy the gradient over as well, if it exists
259- var grad = param . grad ( ) ;
260262 if ( grad is not null ) {
261- p . set_grad ( grad . to ( paramType , device ?? param . device )
262- . with_requires_grad ( grad . requires_grad )
263- . MoveToOtherDisposeScope ( p ) ) ;
263+ using var newGrad = grad . to ( paramType , device ?? param . device )
264+ . with_requires_grad ( grad . requires_grad ) ;
265+ p . grad = newGrad ;
264266 }
265267
266- // Dispose the param and gradient
268+ // Dispose the param
267269 param . Dispose ( ) ;
268- grad ? . Dispose ( ) ;
269270 }
270271 ConditionallyRegisterParameter ( name , p ) ;
271272
@@ -360,11 +361,10 @@ public virtual void zero_grad(bool set_to_none = true)
360361 CheckForErrors ( ) ;
361362
362363 foreach ( var ( _, p ) in named_parameters ( ) ) {
363- var grad = p . grad ( ) ;
364+ using var grad = p . grad ;
364365 if ( grad is not null ) {
365366 if ( set_to_none ) {
366- p . set_grad ( null ) ;
367- grad . DetachFromDisposeScope ( ) . Dispose ( ) ;
367+ p . grad = null ;
368368 } else {
369369 grad . zero_ ( ) ;
370370 }
0 commit comments