Hi Sebastian!



 SebGruber1996:

calling the function ‘n_deriv’ (calling ‘jac’ recursively in a for loop) like this
    for i in [0,1]:
        g[str(i+1)] = lambda y: jac(g[str(i)], y, create_graph=True)

leads to the following error
RecursionError: maximum recursion depth exceeded while calling a Python object



Your error is caused by python scoping rules and is not specific to
pytorch nor torch.autograd.functional.jacobian.
Please see this python FAQ:
Why do lambdas defined in a loop with different values all return the same result? 2
Here is a tweaked version of your code that shows how to “capture” a
local-to-lambda-scope copy of your previously created dictionary entry:
import torch
from torch.autograd.functional import jacobian as jac
print (torch.__version__)

def t(*x):
    return torch.tensor([*x], dtype=torch.float32, requires_grad=True)
    
def f(x, p=5):
    return torch.pow(x, p).sum()

print(f(t(2)))

import sys
sys.setrecursionlimit (20)   # just to trim the verbosely redundant output

def n_deriv_(func, x):
    g = {'0': func}
    
    g['1'] = lambda y: jac(g['0'], y, create_graph=True)
    g['2'] = lambda y: jac(g['1'], y, create_graph=True)
    
    return g['2'](x)

print(n_deriv_(f, t(1)))

def n_deriv_local_scope(func, x):
    g = {'0': func}
    
    for i in [0,1]:
        # g[str(i+1)] = lambda y: jac(g[str(i)], y, create_graph=True)
        g[str(i+1)] = lambda y, gi = g[str (i)]: jac(gi, y, create_graph=True)
    
    return g['2'](x)

print(n_deriv_local_scope(f, t(1)))

def n_deriv(func, x):
    g = {'0': func}
    
    for i in [0,1]:
        g[str(i+1)] = lambda y: jac(g[str(i)], y, create_graph=True)
    
    return g['2'](x)

print ('calling n_deriv ...')
print(n_deriv(f, t(1)))

And here is its output:
1.9.0
tensor(32., grad_fn=<SumBackward0>)
tensor([[20.]], grad_fn=<ViewBackward>)
tensor([[20.]], grad_fn=<ViewBackward>)
calling n_deriv ...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 46, in <module>
  File "<string>", line 43, in n_deriv
  File "<string>", line 41, in <lambda>
  File "<...>\torch\autograd\functional.py", line 482, in jacobian
    outputs = func(*inputs)
  File "<string>", line 41, in <lambda>
  File "<...>\torch\autograd\functional.py", line 482, in jacobian
    outputs = func(*inputs)
  File "<string>", line 41, in <lambda>
  File "<...>\torch\autograd\functional.py", line 482, in jacobian
    outputs = func(*inputs)
  File "<string>", line 41, in <lambda>
  File "<...>\torch\autograd\functional.py", line 482, in jacobian
    outputs = func(*inputs)
  File "<string>", line 41, in <lambda>
  File "<...>\torch\autograd\functional.py", line 482, in jacobian
    outputs = func(*inputs)
  File "<string>", line 41, in <lambda>
RecursionError: maximum recursion depth exceeded while getting the str of an object

Best.
K. Frank