
v1 clip_by_norm 은 단일 벡터. 실전 신경망은 수십 개 파라미터 텐서 (layer 1 W, layer 1 b, layer 2 W, …) 가 있고, 각기 다른 shape. PyTorch torch.nn.utils.clip_grad_norm_ 의 올바른 동작:
total_norm_sq = sum(np.sum(g**2) for g in grads)
total_norm = np.sqrt(total_norm_sq)
clip_coef = min(max_norm / (total_norm + eps), 1.0)
clipped = [g * clip_coef for g in grads]
함수 clip_grad_list(grads, max_norm) 를 완성하세요.
grads: numpy 배열들의 리스트 (각기 다른 shape 가능).(clipped_list, total_norm) — clipped 리스트 (같은 shape), 원본의 global norm (Python float).| # | 이름 | 검증 |
|---|---|---|
| 1 | 반환 (list, float) | |
| 2 | 각 텐서 shape 보존 | |
| 3 | global norm ≤ max_norm → 원본 그대로 | |
| 4 | global norm > max_norm → 전체 shape 스케일 | |
| 5 | 스케일 후 norm == max_norm (정확) | |
| 6 | 영 텐서들 → NaN 없이 그대로 | |
| 7 | 한 텐서만 있을 때 v1 clip_by_norm 과 일치 |
코드를 작성하고 Run 을 눌러보세요.