Download code/tk/lm.py from Lucasgitguy-co/Turbo-Kev-Dictate-1.4B: direct link, hf CLI and curl.
- Browser
- Download file 1.12 kB
-
https://huggingface.co/Lucasgitguy-co/Turbo-Kev-Dictate-1.4B/resolve/main/code/tk/lm.py
- Command line
-
hf download hf://Lucasgitguy-co/Turbo-Kev-Dictate-1.4B/code/tk/lm.py
-
curl -L -o lm.py https://huggingface.co/Lucasgitguy-co/Turbo-Kev-Dictate-1.4B/resolve/main/code/tk/lm.py
1.12 kB
| """LM helpers: run the decoder, then the 248k-vocab head ONLY at the positions that are scored (a full-sequence | |
| head is most of the step time and memory on the M4).""" | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn.functional as F | |
| def parts(model): | |
| m = model.get_base_model() if hasattr(model, "get_base_model") else model | |
| return m.model, m.lm_head | |
| def hidden(model, attention_mask, input_ids=None, inputs_embeds=None): | |
| dec, _ = parts(model) | |
| return dec(input_ids=input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, | |
| use_cache=False).last_hidden_state | |
| def scored_logits(model, h: torch.Tensor, labels: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: | |
| """h (B,T,D), labels (B,T) with -100 = not scored. Returns (logits (N,V) fp32, targets (N,)) for next-token | |
| prediction at every scored position.""" | |
| _, head = parts(model) | |
| y = labels[:, 1:] | |
| m = y != -100 | |
| return head(h[:, :-1][m]).float(), y[m] | |
| def ce(model, h, labels) -> torch.Tensor: | |
| lg, y = scored_logits(model, h, labels) | |
| return F.cross_entropy(lg, y) | |