Repository navigation
Expand file tree
/
Copy pathrecord_training_logits.py
More file actions
103 lines (91 loc) · 3.67 KB
/
Copy pathrecord_training_logits.py
File metadata and controls
103 lines (91 loc) · 3.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""Capture one raw, full-vocabulary score vector from each actor update."""
import functools
import os
from pathlib import Path
import torch
from record_training_ce import begin_step, finish_step
def capture_update(model, update, step, destination, vocab_size):
sample = {}
def capture(_module, _args, kwargs, output):
scores = getattr(output, "logits", None)
if sample or scores is None or scores.ndim != 3:
return
input_ids = kwargs.get("input_ids")
if input_ids is None or input_ids.shape[:2] != scores.shape[:2]:
return
if hasattr(scores, "to_local"):
scores = scores.to_local()
if vocab_size is not None and scores.shape[-1] < vocab_size:
return
mask = kwargs.get("attention_mask")
position = int(mask[0].nonzero()[0].item()) if mask is not None and mask.ndim == 2 else 0
sample.update(
global_step=step,
sequence_position=position,
input_ids=input_ids[0].detach().cpu(),
logits=scores[0, position].detach().float().cpu(),
source_dtype=str(scores.dtype),
)
hook = model.register_forward_hook(capture, with_kwargs=True)
try:
metrics = update()
finally:
hook.remove()
if not sample:
print(f"Step {step}: no raw logits were captured from the policy forward", flush=True)
return metrics
output = Path(destination)
output.mkdir(parents=True, exist_ok=True)
target = output / f"step-{step}.pt"
temporary = target.with_suffix(".tmp")
torch.save(sample, temporary)
temporary.replace(target)
print(f"Saved policy logits for global step {step}: {target}", flush=True)
return metrics
def record_verl_update(update):
@functools.wraps(update)
def wrapped(self, data):
destination = os.environ.get("DLRL_TRAIN_LOGITS_DIR")
if not destination:
return update(self, data)
writer = torch.distributed.get_rank() == 0
step = int(data.meta_info["global_steps"])
config = self.actor_module.config
text_config = getattr(config, "text_config", config)
token = begin_step()
try:
result = (
capture_update(self.actor_module, lambda: update(self, data), step, destination, text_config.vocab_size)
if writer else update(self, data)
)
except BaseException:
finish_step(token, step, aggregate=False)
raise
finish_step(token, step, writer=writer)
return result
return wrapped
def record_nemo_update(update):
@functools.wraps(update)
def wrapped(self, data, loss_fn, eval_mode=False, *args, **kwargs):
call = lambda: update(self, data, loss_fn, eval_mode, *args, **kwargs)
destination = os.environ.get("DLRL_TRAIN_LOGITS_DIR")
if eval_mode or not destination:
return call()
writer = torch.distributed.get_rank() == 0
step = getattr(self, "_dlrl_recorded_step", 0) + 1
config = getattr(self.model, "config", None)
text_config = getattr(config, "text_config", config)
token = begin_step()
try:
result = (
capture_update(self.model, call, step, destination, getattr(text_config, "vocab_size", None))
if writer else call()
)
except BaseException:
finish_step(token, step, aggregate=False)
raise
scope = os.environ.get("DLRL_CE_TARGET_SCOPE", "response")
finish_step(token, step, self.dp_mesh.get_group(), writer=writer, scope=scope)
self._dlrl_recorded_step = step
return result
return wrapped