Repository navigation
Expand file tree
/
Copy pathhf.py
More file actions
795 lines (731 loc) · 32.3 KB
/
Copy pathhf.py
File metadata and controls
795 lines (731 loc) · 32.3 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
"""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 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
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.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_ada
8000
pter_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)
return 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,
)
@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
# -- 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
def prefill(rows: list[list[int]]) -> tuple[torch.Tensor, Any]:
nonlocal attention_mask
lengths = [len(row) for row in rows]
width = max(lengths)
input_ids = torch.full(
(len(rows), width),
self.tokenizer.pad_token_id,
dtype=torch.long,
device=self._device,
)
attention_mask = torch.zeros((len(rows), width), dtype=torch.bool, device=self._device)
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
position_ids = attention_mask.long().cumsum(dim=-1) - 1
position_ids.masked_fill_(~attention_mask, 0)
with torch.no_grad():
hidden, present = self._backbone_forward(
input_ids,
attention_mask=attention_mask,
use_cache=True,
position_ids=position_ids,
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: list[int], active: list[bool], state: Any
) -> tuple[torch.Tensor, Any]:
nonlocal attention_mask
assert attention_mask is not None
active_tensor = torch.tensor(active, dtype=torch.bool, device=self._device)
input_ids = torch.tensor(tokens, dtype=torch.long, device=self._device).unsqueeze(1)
input_ids = torch.where(
active_tensor.unsqueeze(1),
input_ids,
torch.full_like(input_ids, self.tokenizer.pad_token_id),
)
position_ids = attention_mask.long().sum(dim=-1, keepdim=True)
attention_mask = torch.cat((attention_mask, active_tensor.unsqueeze(1)), dim=1)
with torch.no_grad():
hidden, present = self._backbone_forward(
input_ids,
attention_mask=attention_mask,
past_key_values=state,
use_cache=True,
position_ids=position_ids,
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")
self._device = "cpu"
self.capabilities.device = "cpu"
empty_cache()
@property
def device(self) -> str:
"""Current device."""
return self._device