C.W.K.
Stream
Lesson 04 of 06 · published

Persistent tape와 higher-order gradient

~11 min · gradient-tape, persistent, second-derivative

Level 0Level 0
0 XP0/78 lessons0/17 achievements
0/100 XP to next level100 XP to go0% complete

Tape 한 개로 부족할 때

기본 GradientTape는 첫 tape.gradient() 호출 후 리소스를 놓아. 두 상황엔 특별한 패턴이 필요해 — 같은 forward pass에서 여러 gradient 계산, 그리고 second-order (또는 그 이상) gradient.

Persistent tape (tf.GradientTape(persistent=True))는 여러 번 gradient() 호출 가능. trade-off: tape가 모든 중간 tensor 참조 잡고 있어서 GC 막아. 끝나면 항상 del tape — 특히 빡빡한 training loop에서.

Higher-order gradient는 중첩 tape 써. 바깥 tape가 안쪽 tape의 gradient 계산을 녹화해서 outer.gradient(inner_grad, x)가 2계 도함수 반환.

벡터값 함수의 Jacobian은 tape.jacobian(y, x) — shape는 output_shape + input_shape.

Code

Persistent tape·python
import tensorflow as tf

x = tf.Variable(2.0)

# Default tape: one gradient() call only
with tf.GradientTape() as tape:
    y = x ** 3
dy_dx = tape.gradient(y, x)        # 3x² = 12
# tape.gradient(y, x)               # ERROR: tape released

# Persistent tape: multiple calls allowed
with tf.GradientTape(persistent=True) as tape:
    y = x ** 3

dy_dx = tape.gradient(y, x)        # 12
d2y_dx2 = tape.gradient(dy_dx, x)  # 6x = 12
del tape   # IMPORTANT for memory
Nested tape — second derivative·python
import tensorflow as tf

x = tf.Variable(2.0)

with tf.GradientTape() as t2:
    with tf.GradientTape() as t1:
        y = x * x * x       # y = x³
    dy_dx = t1.gradient(y, x)        # 3x² = 12

d2y_dx2 = t2.gradient(dy_dx, x)      # 6x = 12
print(f"f'(2) = {dy_dx.numpy()}")    # 12.0
print(f"f''(2) = {d2y_dx2.numpy()}") # 12.0

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.