Repository navigation
Expand file tree
/
Copy pathhf.py
More file actions
1008 lines (928 loc) · 41.1 KB
/
8000
Copy pathhf.py
File metadata and controls
1008 lines (928 loc) · 41.1 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Hugging Face causal-LM backend.
Key property: the LM head is **never** run over a whole sequence. Both
scoring and training call the decoder backbone directly to obtain
``[1, T, H]`` hidden states, gather the selected positions into ``[N, H]``, and
project only those. Even generation projects a single position per step. For
a 152k-vocabulary model at sequence length 768 this avoids a 445 MB fp32 logit
tensor per forward pass, which is the difference between fitting on a 16 GB
card and not.
"""
from __future__ import annotations
import copy
import gc
import inspect
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import torch
from miniverl.agent.transcript import TokenizerLike
from miniverl.config.models import (
LoRAConfig,
Precision,
Quantization,
StudentModelConfig,
TeacherModelConfig,
)
from miniverl.errors import BackendError, MissingDependencyError
from miniverl.models.adapters import ArchitectureAdapter
from miniverl.models.base import BackendCapabilities, CausalLMBackend, GenerationOutput
from miniverl.models.sampling import (
run_cached_padded_generation,
run_generation,
run_greedy_padded_generation,
)
from miniverl.utils.lazy import have_module, require_peft, require_transformers
__all__ = ["HFBackend", "resolve_dtype", "supports_bfloat16"]
def supports_bfloat16(device: str) -> bool:
"""``True`` when bf16 is usable on ``device``."""
if device.startswith("cuda"):
return bool(torch.cuda.is_available() and torch.cuda.is_bf16_supported())
return hasattr(torch, "bfloat16")
def resolve_dtype(precision: Precision, device: str) -> torch.dtype:
"""Turn ``auto`` into a concrete dtype for ``device``."""
if precision is Precision.FLOAT32:
return torch.float32
if precision is Precision.BFLOAT16:
return torch.bfloat16
if precision is Precision.FLOAT16:
return torch.float16
if device.startswith("cuda"):
return torch.bfloat16 if supports_bfloat16(device) else torch.float16
return torch.float32
def _quantization_config(quantization: Quantization, compute_dtype: torch.dtype) -> Any:
if quantization is Quantization.NONE:
return None
if not have_module("bitsandbytes"):
raise MissingDependencyError(
"bitsandbytes", "cuda", f"{quantization.value} weight quantization"
)
transformers = require_transformers("Quantized model loading")
if quantization is Quantization.NF4:
return transformers.BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=compute_dtype,
)
return transformers.BitsAndBytesConfig(load_in_8bit=True)
def _dtype_kwarg_name() -> str:
"""Name of the dtype keyword this transformers version wants.
``torch_dtype`` was renamed to ``dtype`` in transformers 4.56 and the old
name warns loudly on 5.x. The signature is often ``**kwargs``, so version
comparison is more reliable than introspection; introspection is kept as a
fallback for forks that do declare the parameter.
"""
transformers = require_transformers("Model loading")
version = str(getattr(transformers, "__version__", "0"))
try:
parts = [int(p) for p in version.split(".")[:2]]
major, minor = [*parts, 0, 0][:2]
except ValueError: # pragma: no cover - unusual version strings
major, minor = 0, 0
if (major, minor) >= (4, 56):
return "dtype"
signature = inspect.signature(transformers.AutoModelForCausalLM.from_pretrained)
return "dtype" if "dtype" in signature.parameters else "torch_dtype"
def _from_pretrained_kwargs(dtype: torch.dtype) -> dict[str, Any]:
"""Build the dtype keyword argument for ``from_pretrained``."""
return {_dtype_kwarg_name(): dtype}
def _adapter_probe_kwargs(*, revision: str | None, local_files_only: bool) -> dict[str, Any]:
"""Build PEFT auto-detection kwargs across transformers 4.x and 5.x.
Transformers 4.x already forwards the top-level ``local_files_only`` value
to its PEFT-config probe, so repeating it in ``adapter_kwargs`` raises a
duplicate-keyword ``TypeError``. Transformers 5.x stopped forwarding that
policy, so it must be supplied explicitly there to preserve the zero-network
contract.
"""
transformers = require_transformers("Model loading")
version = str(getattr(transformers, "__version__", "0"))
try:
major = int(version.split(".", maxsplit=1)[0])
except ValueError: # pragma: no cover - unusual version strings
major = 0
kwargs: dict[str, Any] = {"revision": revision}
if major >= 5:
kwargs["local_files_only"] = local_files_only
return kwargs
def _static_generation_cache(
config: Any,
*,
batch_size: int,
max_cache_len: int,
device: str,
dtype: torch.dtype,
) -> Any:
"""Construct the supported Transformers static cache across 4.x and 5.x."""
transformers = require_transformers("Static cached generation")
constructor = transformers.StaticCache
parameters = inspect.signature(constructor).parameters
kwargs: dict[str, Any] = {
"config": config,
"max_cache_len": max_cache_len,
}
if "max_batch_size" in parameters:
kwargs["max_batch_size"] = batch_size
if "device" in parameters:
kwargs["device"] = device
if "dtype" in parameters:
kwargs["dtype"] = dtype
return constructor(**kwargs)
class HFBackend(CausalLMBackend):
"""Local Hugging Face causal LM, optionally quantized and LoRA-adapted."""
def __init__(
self,
*,
model: Any,
tokenizer: TokenizerLike,
model_id: str,
model_revision: str | None,
device: str,
dtype: torch.dtype,
quantization: Quantization,
gradient_checkpointing: bool,
attn_implementation: str,
lora: bool,
adapter_provenance: dict[str, Any] | None = None,
) -> None:
self.model = model
self.tokenizer = tokenizer
self.model_id = model_id
self.model_revision = model_revision
self._device = device
self._dtype = dtype
self._source_spec: StudentModelConfig | TeacherModelConfig | None = None
self.adapter_provenance = adapter_provenance
self.adapter = ArchitectureAdapter.resolve(model)
self._cached_generation_backbone: Any | None = None
num_params = sum(p.numel() for p in model.parameters())
num_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
self.capabilities = BackendCapabilities(
name=model_id,
device=device,
dtype=str(dtype).replace("torch.", ""),
vocab_size=self.adapter.vocab_size,
hidden_size=self.adapter.hidden_size,
tied_embeddings=self.adapter.tied_embeddings,
quantization=quantization.value,
gradient_checkpointing=gradient_checkpointing,
lora=lora,
attn_implementation=attn_implementation,
num_parameters=num_params,
num_trainable_parameters=num_trainable,
)
# -- construction ------------------------------------------------------
@classmethod
def load(
cls,
spec: StudentModelConfig | TeacherModelConfig,
*,
device: str,
tokenizer: TokenizerLike,
trainable: bool,
local_files_only: bool = False,
protocol_version: str | None = None,
student_adapter_name: str = "default",
) -> HFBackend:
"""Load a model from a local path or the Hub."""
transformers = require_transformers("Loading a Hugging Face causal LM")
dtype = resolve_dtype(spec.dtype, device)
quantization = spec.quantization
adapter_provenance = None
validated_adapter = None
if spec.adapter is not None:
if isinstance(spec, TeacherModelConfig):
from miniverl.models.adapter_io import validate_teacher_adapter
validated_adapter = validate_teacher_adapter(
spec.adapter,
spec,
tokenizer_fingerprint=tokenizer.fingerprint,
protocol_version=protocol_version,
local_files_only=local_files_only,
)
else:
from miniverl.models.adapter_io import validate_student_adapter
validated_adapter = validate_student_adapter(
spec.adapter,
spec,
tokenizer_fingerprint=tokenizer.fingerprint,
local_files_only=local_files_only,
)
adapter_provenance = validated_adapter.provenance
kwargs: dict[str, Any] = {
"revision": spec.revision,
"trust_remote_code": spec.trust_remote_code,
"local_files_only": local_files_only,
# Transformers performs a separate PEFT-config probe before loading
# the base model. Its policy propagation differs between 4.x and
# 5.x, so build compatible explicit probe kwargs.
"adapter_kwargs": _adapter_probe_kwargs(
revision=spec.revision,
local_files_only=local_files_only,
),
"attn_implementation": spec.attn_implementation,
**_from_pretrained_kwargs(dtype),
}
quant_config = _quantization_config(quantization, dtype)
if quant_config is not None:
kwargs["quantization_config"] = quant_config
kwargs["device_map"] = {"": device}
try:
model_source = spec.model_id
if local_files_only and not Path(spec.model_id).exists():
# Resolve the cached snapshot before entering Transformers.
# Some Transformers/Hub version combinations perform an
# adapter-discovery HEAD request even when the top-level model
# load received local_files_only=True. A concrete snapshot
# path makes the zero-network contract unambiguous.
from huggingface_hub import snapshot_download
model_source = snapshot_download(
repo_id=spec.model_id,
revision=spec.revision,
local_files_only=True,
)
model = transformers.AutoModelForCausalLM.from_pretrained(model_source, **kwargs)
except (OSError, ValueError) as exc:
revision = f" at revision {spec.revision!r}" if spec.revision else ""
preload = f"hf download {spec.model_id}"
if spec.revision:
preload += f" --revision {spec.revision}"
offline_hint = (
f"offline mode found no complete cached model snapshot; preload it online "
f"with `{preload}`. "
if local_files_only
else ""
)
raise BackendError(
f"could not load model {spec.model_id!r}{revision}",
hint=(
offline_hint
+ "check the model id and revision and that any gated license has been "
f"accepted on the Hub. Original error: {exc}"
),
) from exc
if quant_config is None:
model.to(device)
lora_enabled = False
gradient_checkpointing = getattr(spec, "gradient_checkpointing", False)
if trainable:
lora_spec = getattr(spec, "lora", None)
if isinstance(spec, StudentModelConfig) and spec.adapter is not None:
assert validated_adapter is not None
peft = require_peft("Loading a trainable existing student adapter")
if quant_config is not None and spec.prepare_kbit_training:
model = peft.prepare_model_for_kbit_training(
model, use_gradient_checkpointing=gradient_checkpointing
)
elif quant_config is not None:
for parameter in model.parameters():
parameter.requires_grad_(False)
try:
model = peft.PeftModel.from_pretrained(
model,
str(validated_adapter.snapshot_dir),
adapter_name=student_adapter_name,
is_trainable=True,
local_files_only=True,
)
except (OSError, ValueError) as exc:
raise BackendError(
f"could not attach trainable student adapter {spec.adapter.path!r}: {exc}",
hint="verify the pinned adapter/base pair and PEFT target modules",
) from exc
lora_enabled = True
elif isinstance(lora_spec, LoRAConfig) and lora_spec.enabled:
model = cls._attach_lora(
model,
lora_spec,
quantized=quant_config is not None,
gradient_checkpointing=gradient_checkpointing,
adapter_name=student_adapter_name,
prepare_kbit_training=getattr(spec, "prepare_kbit_training", True),
)
lora_enabled = True
if gradient_checkpointing:
model.gradient_checkpointing_enable()
enable_grads = getattr(model, "enable_input_require_grads", None)
if callable(enable_grads):
enable_grads()
model.train()
else:
if isinstance(spec, TeacherModelConfig) and spec.adapter is not None:
assert validated_adapter is not None
peft = require_peft("Loading a frozen teacher adapter")
try:
model = peft.PeftModel.from_pretrained(
model,
str(validated_adapter.snapshot_dir),
is_trainable=False,
local_files_only=True,
)
except (OSError, ValueError) as exc:
raise BackendError(
f"could not attach teacher adapter {spec.adapter.path!r}: {exc}",
hint="verify the adapter/base pair and its PEFT target modules",
) from exc
lora_enabled = True
for param in model.parameters():
param.requires_grad_(False)
model.eval()
if any(param.requires_grad for param in model.parameters()):
raise BackendError("teacher adapter load left trainable teacher parameters")
if getattr(model, "config", None) is not None:
model.config.use_cache = not (trainable and gradient_checkpointing)
backend = cls(
model=model,
tokenizer=tokenizer,
model_id=spec.model_id,
model_revision=spec.revision,
device=device,
dtype=dtype,
quantization=quantization,
gradient_checkpointing=bool(gradient_checkpointing),
attn_implementation=spec.attn_implementation,
lora=lora_enabled,
adapter_provenance=adapter_provenance,
)
backend._source_spec = spec.model_copy(deep=True)
return backend
@staticmethod
def _attach_lora(
model: Any,
spec: LoRAConfig,
*,
quantized: bool,
gradient_checkpointing: bool,
adapter_name: str = "default",
prepare_kbit_training: bool = True,
) -> Any:
peft = require_peft("LoRA / QLoRA training")
if quantized and prepare_kbit_training:
model = peft.prepare_model_for_kbit_training(
model, use_gradient_checkpointing=gradient_checkpointing
)
elif quantized:
# Keep the one physical base byte/dtype-equivalent to a frozen
# separately loaded teacher. PEFT will mark the newly attached LoRA
# trainable; the quantized base itself remains frozen.
for parameter in model.parameters():
parameter.requires_grad_(False)
config = peft.LoraConfig(
r=spec.r,
lora_alpha=spec.alpha,
lora_dropout=spec.dropout,
bias=spec.bias,
target_modules=list(spec.target_modules),
task_type="CAUSAL_LM",
)
try:
return peft.get_peft_model(model, config, adapter_name=adapter_name)
except ValueError as exc:
raise BackendError(
f"could not attach LoRA adapters: {exc}",
hint="check models.student.lora.target_modules against the model's "
"module names (for Qwen: q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj)",
) from exc
# -- forward helpers ----------------------------------------------------
def _backbone_forward(
self,
input_ids: torch.Tensor,
*,
attention_mask: torch.Tensor | None = None,
past_key_values: Any = None,
use_cache: bool = False,
position_ids: torch.Tensor | None = None,
cache_position: torch.Tensor | None = None,
cached_generation: bool = False,
) -> tuple[torch.Tensor, Any]:
backbone = (
self._cached_generation_backbone
if cached_generation and self._cached_generation_backbone is not None
else self.adapter.backbone
)
kwargs: dict[str, Any] = {"input_ids": input_ids, "use_cache": use_cache}
if attention_mask is not None:
kwargs["attention_mask"] = attention_mask
if past_key_values is not None:
kwargs["past_key_values"] = past_key_values
if position_ids is not None:
kwargs["position_ids"] = position_ids
if cache_position is not None:
kwargs["cache_position"] = cache_position
outputs = backbone(**kwargs)
hidden = getattr(outputs, "last_hidden_state", None)
if hidden is None:
hidden = outputs[0]
return hidden, getattr(outputs, "past_key_values", None)
def enable_cached_generation_compilation(self) -> None:
"""Compile only the cached decode backbone, with CUDA graphs disabled."""
if self._cached_generation_backbone is not None:
return
if not self._device.startswith("cuda"):
raise BackendError(
"compiled hf_cached generation requires CUDA",
hint="set rollout.compile_backend=false on CPU",
)
try:
self._cached_generation_backbone = torch.compile(
self.adapter.backbone,
dynamic=True,
options={"triton.cudagraphs": False},
)
except Exception as exc:
raise BackendError(
"could not initialize compiled hf_cached generation",
hint="set rollout.compile_backend=false to use the eager KV-cache path",
) from exc
@staticmethod
def _active_peft_adapter_name(model: Any) -> str:
active_adapters = getattr(model, "active_adapters", None)
if callable(active_adapters):
names = list(active_adapters())
else:
active = getattr(model, "active_adapter", None)
names = [active] if isinstance(active, str) else []
if len(names) != 1 or not isinstance(names[0], str):
raise BackendError(
"compiled NF4 rollout requires exactly one active student adapter",
hint="select one LoRA adapter before constructing the rollout runtime",
)
return names[0]
def build_cached_generation_mirror(self) -> HFBackend:
"""Build a local BF16 rollout mirror derived from this NF4 actor.
The training actor remains the policy source of truth. The mirror loads
the same cached base snapshot, uses Transformers' supported dequantize
operation, and receives the actor's exact live adapter tensors before
every synchronized rollout.
"""
if self.capabilities.quantization != Quantization.NF4.value:
raise BackendError("a cached generation mirror is only defined for an NF4 actor")
if not self._device.startswith("cuda"):
raise BackendError("the NF4 BF16 rollout mirror requires CUDA")
spec = self._source_spec
if not isinstance(spec, StudentModelConfig):
raise BackendError(
"the NF4 actor has no reconstructable student model specification",
hint="construct the actor with HFBackend.load before enabling compiled rollout",
)
adapter_name = self._active_peft_adapter_name(self.model)
peft_configs = getattr(self.model, "peft_config", None)
if not isinstance(peft_configs, dict) or adapter_name not in peft_configs:
raise BackendError("the active NF4 adapter configuration is unavailable")
mirror: HFBackend | None = None
try:
mirror = type(self).load(
spec,
device=self._device,
tokenizer=self.tokenizer,
trainable=False,
local_files_only=True,
)
dequantize = getattr(mirror.model, "dequantize", None)
if not callable(dequantize):
raise BackendError(
"the loaded NF4 base cannot be expanded for compiled rollout",
hint="use rollout.compile_backend=false with this Transformers backend",
)
dequantized = dequantize()
if dequantized is not None:
mirror.model = dequantized
peft = require_peft("Compiled NF4 rollout mirror")
adapter_config = copy.deepcopy(peft_configs[adapter_name])
adapter_config.inference_mode = False
mirror.model = peft.get_peft_model(
mirror.model,
adapter_config,
adapter_name=adapter_name,
)
mirror.adapter = ArchitectureAdapter.resolve(mirror.model)
mirror.model_id = self.model_id
mirror.model_revision = self.model_revision
mirror.adapter_provenance = self.adapter_provenance
mirror.capabilities.name = self.capabilities.name
mirror.capabilities.quantization = Quantization.NONE.value
mirror.capabilities.lora = True
mirror.capabilities.num_parameters = sum(
parameter.numel() for parameter in mirror.model.parameters()
)
mirror.capabilities.num_trainable_parameters = sum(
parameter.numel()
for parameter in mirror.model.parameters()
if parameter.requires_grad
)
mirror.model.config.use_cache = True
mirror.model.eval()
from miniverl.runtime.policy_sync import adapter_tensor_digest
self.synchronize_cached_generation_mirror(
mirror,
expected_adapter_digest=adapter_tensor_digest(self),
)
return mirror
except BaseException as exc:
if mirror is not None:
mirror.discard_cached_generation_mirror()
if isinstance(exc, BackendError):
raise
raise BackendError(
"could not construct the compiled NF4 rollout mirror",
hint=(
"the training actor is unchanged; set rollout.compile_backend=false "
f"to use it directly. Original error: {exc}"
),
) from exc
def synchronize_cached_generation_mirror(
self,
mirror: HFBackend,
*,
expected_adapter_digest: str,
) -> None:
"""Copy and verify one live adapter state before policy activation."""
from miniverl.runtime.policy_sync import adapter_tensor_digest
source_digest = adapter_tensor_digest(self)
if source_digest != expected_adapter_digest:
raise BackendError(
"the actor adapter changed after rollout policy identity construction",
hint="rebuild the policy identity and retry the synchronized rollout",
)
mirror.load_trainable_state_dict(self.trainable_state_dict())
mirror_digest = adapter_tensor_digest(mirror)
if mirror_digest != source_digest:
raise BackendError(
"the BF16 rollout mirror does not exactly match the live actor adapter",
hint="disable compiled rollout; generation was not started",
)
mirror.model.eval()
def discard_cached_generation_mirror(self) -> None:
"""Invalidate an owned rollout mirror and release its CUDA allocations."""
self._cached_generation_backbone = None
self.__dict__.pop("adapter", None)
self.__dict__.pop("model", None)
gc.collect()
from miniverl.utils.gpu import empty_cache
empty_cache()
# -- generation ---------------------------------------------------------
def generate(
self,
prefix_token_ids: Sequence[int],
*,
max_new_tokens: int,
stop_sequences: Sequence[str] = (),
temperature: float = 1.0,
top_p: float = 1.0,
top_k: int = 0,
seed: int | None = None,
record_logprobs: bool = False,
) -> GenerationOutput:
"""Sample a continuation, projecting one position per step."""
was_training = self.model.training
self.model.eval()
generator = torch.Generator(device="cpu")
generator.manual_seed(seed if seed is not None else 0)
cache_flag = getattr(self.model.config, "use_cache", True)
self.model.config.use_cache = True
def step(new_ids: list[int], state: Any) -> tuple[torch.Tensor, Any]:
ids = torch.tensor([new_ids], dtype=torch.long, device=self._device)
with torch.no_grad():
hidden, present = self._backbone_forward(ids, past_key_values=state, use_cache=True)
logits = self.adapter.lm_head(hidden[:, -1, :])
return logits[0].float(), present
try:
return run_generation(
step=step,
prefix_token_ids=prefix_token_ids,
decode=self.tokenizer.decode,
eos_token_id=self.tokenizer.eos_token_id,
max_new_tokens=max_new_tokens,
stop_sequences=stop_sequences,
temperature=temperature,
top_p=top_p,
top_k=top_k,
generator=generator,
record_logprobs=record_logprobs,
)
finally:
self.model.config.use_cache = cache_flag
if was_training:
self.model.train()
def generate_batch(
self,
prefix_token_ids: Sequence[Sequence[int]],
*,
max_new_tokens: int,
stop_sequences: Sequence[str] = (),
temperature: float = 0.0,
top_p: float = 1.0,
top_k: int = 0,
seeds: Sequence[int | None] | None = None,
record_logprobs: bool = False,
) -> list[GenerationOutput]:
"""Use one masked padded forward per greedy decoding step."""
if temperature != 0.0:
return super().generate_batch(
prefix_token_ids,
max_new_tokens=max_new_tokens,
stop_sequences=stop_sequences,
temperature=temperature,
top_p=top_p,
top_k=top_k,
seeds=seeds,
record_logprobs=record_logprobs,
)
was_training = self.model.training
self.model.eval()
def step(rows: list[list[int]]) -> torch.Tensor:
lengths = [len(row) for row in rows]
width = max(lengths)
ids = torch.full(
(len(rows), width),
self.tokenizer.pad_token_id,
dtype=torch.long,
device=self._device,
)
mask = torch.zeros((len(rows), width), dtype=torch.bool, device=self._device)
for index, row in enumerate(rows):
ids[index, : len(row)] = torch.tensor(row, dtype=torch.long, device=self._device)
mask[index, : len(row)] = True
with torch.no_grad():
hidden, _ = self._backbone_forward(ids, attention_mask=mask, use_cache=False)
positions = torch.tensor(
[length - 1 for length in lengths], dtype=torch.long, device=self._device
)
selected = hidden[torch.arange(len(rows), device=self._device), positions]
return self.adapter.lm_head(selected)
try:
return run_greedy_padded_generation(
step=step,
prefix_token_ids=prefix_token_ids,
decode=self.tokenizer.decode,
eos_token_id=self.tokenizer.eos_token_id,
max_new_tokens=max_new_tokens,
stop_sequences=stop_sequences,
record_logprobs=record_logprobs,
)
finally:
if was_training:
self.model.train()
def generate_batch_cached(
self,
prefix_token_ids: Sequence[Sequence[int]],
*,
max_new_tokens: int,
stop_sequences: Sequence[str] = (),
temperature: float = 0.0,
top_p: float = 1.0,
top_k: int = 0,
seeds: Sequence[int | None] | None = None,
record_logprobs: bool = False,
) -> list[GenerationOutput]:
"""Decode a physical batch with one prefill and an incremental KV cache."""
if not prefix_token_ids:
return []
if any(not row for row in prefix_token_ids):
raise ValueError("cached generation cannot contain an empty prompt")
chosen_seeds = list(seeds or [0] * len(prefix_token_ids))
if len(chosen_seeds) != len(prefix_token_ids):
raise ValueError("generate_batch_cached needs exactly one seed per prompt")
generators = []
for seed in chosen_seeds:
generator = torch.Generator(device="cpu")
generator.manual_seed(int(seed or 0))
generators.append(generator)
was_training = self.model.training
self.model.eval()
cache_flag = getattr(self.model.config, "use_cache", True)
self.model.config.use_cache = True
attention_mask: torch.Tensor | None = None
attention_workspace: torch.Tensor | None = None
attention_length = 0
next_position_ids: torch.Tensor | None = None
all_active: torch.Tensor | None = None
mask_required = False
def prefill(rows: list[list[int]]) -> tuple[torch.Tensor, Any]:
nonlocal attention_length, attention_mask, attention_workspace
nonlocal all_active, mask_required, next_position_ids
lengths = [len(row) for row in rows]
width = max(lengths)
mask_required = any(length != width for length in lengths)
input_ids = torch.full(
(len(rows), width),
self.tokenizer.pad_token_id,
dtype=torch.long,
device=self._device,
)
attention_workspace = torch.zeros(
(len(rows), width + max_new_tokens),
dtype=torch.bool,
device=self._device,
)
attention_mask = attention_workspace[:, :width]
for index, row in enumerate(rows):
input_ids[index, : len(row)] = torch.tensor(
row, dtype=torch.long, device=self._device
)
attention_mask[index, : len(row)] = True
attention_length = width
position_ids = attention_mask.long().cumsum(dim=-1) - 1
position_ids.masked_fill_(~attention_mask, 0)
next_position_ids = torch.tensor(
lengths, dtype=torch.long, device=self._device
).unsqueeze(1)
all_active = torch.ones(len(rows), dtype=torch.bool, device=self._device)
cache_position = torch.arange(width, dtype=torch.long, device=self._device)
cache = _static_generation_cache(
self.model.config,
batch_size=len(rows),
max_cache_len=width + max_new_tokens,
device=self._device,
dtype=self._dtype,
)
with torch.inference_mode():
hidden, present = self._backbone_forward(
input_ids,
attention_mask=attention_mask if mask_required else None,
past_key_values=cache,
use_cache=True,
position_ids=position_ids,
cache_position=cache_position,
cached_generation=True,
)
positions = torch.tensor(
[length - 1 for length in lengths], dtype=torch.long, device=self._device
)
selected = hidden[torch.arange(len(rows), device=self._device), positions]
logits = self.adapter.lm_head(selected)
return logits, present
def decode_step(
tokens: Sequence[int] | torch.Tensor, active: list[bool], state: Any
) -> tuple[torch.Tensor, Any]:
nonlocal attention_length, attention_mask, next_position_ids
nonlocal mask_required
assert attention_workspace is not None
assert all_active is not None
assert next_position_ids is not None
active_tensor = (
all_active
if all(active)
else torch.tensor(active, dtype=torch.bool, device=self._device)
)
if not all(active):
mask_required = True
input_ids = torch.as_tensor(tokens, dtype=torch.long, device=self._device).reshape(
-1, 1
)
input_ids = torch.where(
active_tensor.unsqueeze(1),
input_ids,
torch.full_like(input_ids, self.tokenizer.pad_token_id),
)
position_ids = next_position_ids
cache_position = torch.tensor([attention_length], dtype=torch.long, device=self._device)
attention_workspace[:, attention_length] = active_tensor
attention_length += 1
attention_mask = attention_workspace[:, :attention_length]
next_position_ids = next_position_ids + active_tensor.unsqueeze(1)
with torch.inference_mode():
hidden, present = self._backbone_forward(
input_ids,
attention_mask=attention_mask if mask_required else None,
past_key_values=state,
use_cache=True,
position_ids=position_ids,
cache_position=cache_position,
cached_generation=True,
)
logits = self.adapter.lm_head(hidden[:, -1, :])
return logits, present
try:
try:
return run_cached_padded_generation(
prefill=prefill,
decode_step=decode_step,
prefix_token_ids=prefix_token_ids,
decode=self.tokenizer.decode,
eos_token_id=self.tokenizer.eos_token_id,
max_new_tokens=max_new_tokens,
stop_sequences=stop_sequences,
temperature=temperature,
top_p=top_p,
top_k=top_k,
generators=generators,
record_logprobs=record_logprobs,
)
except torch.OutOfMemoryError:
raise
except Exception as exc:
if self._cached_generation_backbone is None:
raise
raise BackendError(
"compiled hf_cached generation failed",
hint="set rollout.compile_backend=false to use the eager KV-cache path",
) from exc
finally:
self.model.config.use_cache = cache_flag
if was_training:
self.model.train()
# -- scoring ------------------------------------------------------------
def hidden_states_at(
self,
token_ids: Sequence[int],
positions: Sequence[int],
*,
with_grad: bool = False,
) -> torch.Tensor:
"""Backbone hidden states gathered at ``positions``; no full-sequence logits."""
ids = torch.tensor([list(token_ids)], dtype=torch.long, device=self._device)
index = torch.tensor(list(positions), dtype=torch.long, device=self._device)
context = torch.enable_grad() if with_grad else torch.no_grad()
with context:
hidden, _ = self._backbone_forward(ids, use_cache=False)
return hidden[0].index_select(0, index)
def hidden_states_at_batch(
self,
batch: Any,
*,
with_grad: bool = False,
) -> torch.Tensor:
"""Gather selected states from one masked padded backbone forward."""
context = torch.enable_grad() if with_grad else torch.no_grad()
with context:
hidden, _ = self._backbone_forward(
batch.input_ids,
attention_mask=batch.attention_mask,
use_cache=False,
)
return hidden[batch.selected_batch_indices, batch.selected_positions]
def project(self, hidden: torch.Tensor) -> torch.Tensor:
"""Apply the LM head to selected hidden states."""
head = self.adapter.lm_head
weight_dtype = getattr(head, "weight", None)
if weight_dtype is not None and hidden.dtype != weight_dtype.dtype:
hidden = hidden.to(weight_dtype.dtype)
return head(hidden)
# -- training -----------------------------------------------------------
def set_train(self, mode: bool) -> None:
"""Switch train/eval mode."""
self.model.train(mode)
def trainable_parameters(self) -> list[torch.nn.Parameter]:
"""Parameters requiring gradients (the LoRA adapters under QLoRA)."""
return [p for p in self.model.parameters() if p.requires_grad]
def trainable_state_dict(self) -> dict[str, torch.Tensor]:
"""CPU copy of the trainable weights only."""
return {
name: param.detach().to("cpu").clone()
for name, param in self.model.named_parameters()
if param.requires_grad
}
def load_trainable_state_dict(self, state: dict[str, torch.Tensor]) -> None:
"""Restore trainable weights in place."""
own = dict(self.model.named_parameters())
expected = {name for name, parameter in own.items() if parameter.requires_grad}
unknown = sorted(set(state).difference(expected))
missing = sorted(expected.difference(state))
if unknown:
raise BackendError(
f"checkpoint contains {len(unknown)} unknown parameter names, e.g. {unknown[0]}",
hint="the checkpoint was written by a different model or LoRA config",
)
if missing:
raise BackendError(
f"checkpoint is missing {len(missing)} trainable parameters, e.g. {missing[0]}",
hint="the checkpoint is incomplete or was written by a different LoRA config",
)
mismatched = [
(name, tuple(value.shape), tuple(own[name].shape))
for name, value in state.items()
if value.shape != own[name].shape
]
if mismatched:
name, actual, expected_shape = mismatched[0]
raise BackendError(
f"checkpoint parameter {name!r} has shape {actual}, expected {expected_shape}",
hint="the checkpoint was written by a different model or LoRA config",
)
with torch.no_grad():
for name, value in state.items():
own[name].copy_(value.to(own[name].device, own[name].dtype))
# -- placement -----------------------------------------------------------
def to_device(self, device: str) -> None:
"""Move the model, unless it is bitsandbytes-quantized (pinned at load)."""
if self.capabilities.quantization != "none" and device != self._device:
raise BackendError(
"a bitsandbytes-quantized model cannot be moved between devices after loading",
hint="use memory.strategy: resident for quantized models, or load the "
"model unquantized",
)
self.model.to(device)
self._device = device
self.capabilities.device = device
def release(self) -> None:
"""Move to host memory and free the CUDA caching allocator's blocks."""
from miniverl.utils.gpu import empty_cache
if self.capabilities.quantization == "none":
self.model.to("cpu")