Instructions to use Mergeability/beetle-humanscale-nld-eng with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Mergeability/beetle-humanscale-nld-eng with Transformers:
# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Mergeability/beetle-humanscale-nld-eng", device_map="auto") - Notebooks
- Google Colab
- Kaggle
consolidate: absorb csp__naive
Browse files- csp__naive/.gitattributes +35 -0
- csp__naive/README.md +43 -0
- csp__naive/config.json +23 -0
- csp__naive/generation_config.json +4 -0
- csp__naive/model.safetensors +3 -0
- csp__naive/pico_decoder.py +342 -0
- csp__naive/tokenizer.json +0 -0
- csp__naive/tokenizer_config.json +13 -0
csp__naive/.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
csp__naive/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags: [model-merging, mergeability, training-free, quotient-merge-distance]
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# beetle-humanscale-nld-eng__csp__naive
|
| 7 |
+
|
| 8 |
+
Training-free merged checkpoint from the **Mergeability** sweep
|
| 9 |
+
(`benchmark/emit_lm.py --real`), produced by weight-space merging of two independently
|
| 10 |
+
trained parents. No gradient steps were taken.
|
| 11 |
+
|
| 12 |
+
| field | value |
|
| 13 |
+
|---|---|
|
| 14 |
+
| pair_id | `beetle-humanscale-nld-eng` |
|
| 15 |
+
| parent_a | `Beetle-HumanScale/beetle-monolingual-humanscale-nld` |
|
| 16 |
+
| parent_b | `Beetle-HumanScale/beetle-monolingual-humanscale-eng` |
|
| 17 |
+
| ceiling | `Beetle-HumanScale/beetle-bilingual-l2-50-simultaneous-b2-humanscale-nld-eng` |
|
| 18 |
+
| operator | `csp` |
|
| 19 |
+
| alignment | `naive` |
|
| 20 |
+
| align_method | `permutation` |
|
| 21 |
+
| regime | `shared_base` |
|
| 22 |
+
| eval_langs | `eng+nld` |
|
| 23 |
+
| nll_merge | `10.5288` |
|
| 24 |
+
| nll_floor | `6.3583` |
|
| 25 |
+
| param_coverage | `1.0` |
|
| 26 |
+
| MS | `-13.6334` |
|
| 27 |
+
|
| 28 |
+
## How it was made
|
| 29 |
+
|
| 30 |
+
Parents were loaded, activations extracted on a shared calibration corpus, and the merge applied
|
| 31 |
+
either **naive** (parents combined in their own coordinates) or **aligned** (parent B carried into
|
| 32 |
+
parent A's residual-stream basis via `common.alignment.residual_basis_map` before merging —
|
| 33 |
+
permutation for same-width pairs, orthogonal/rectangular for cross-width).
|
| 34 |
+
|
| 35 |
+
`MS` is the recovery score from `common.eval.mergeability_score` (merged vs. floor vs. ceiling), the
|
| 36 |
+
same normalisation used by Zhou et al., so it is comparable across rows of the sweep.
|
| 37 |
+
|
| 38 |
+
## Caveats
|
| 39 |
+
|
| 40 |
+
Sub-1B merges are noisy; an aligned signal where the naive one is noise is the finding, not a bug.
|
| 41 |
+
Rows without a joint ceiling are floor-relative and must not be read as absolute recovery.
|
| 42 |
+
|
| 43 |
+
Generated automatically — see the [mergeability repo](https://github.com/suchirsalhan/mergeability).
|
csp__naive/config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation_hidden_dim": 3072,
|
| 3 |
+
"architectures": [
|
| 4 |
+
"PicoDecoderHF"
|
| 5 |
+
],
|
| 6 |
+
"attention_n_heads": 12,
|
| 7 |
+
"attention_n_kv_heads": 1,
|
| 8 |
+
"auto_map": {
|
| 9 |
+
"AutoConfig": "pico_decoder.PicoDecoderHFConfig",
|
| 10 |
+
"AutoModelForCausalLM": "pico_decoder.PicoDecoderHF"
|
| 11 |
+
},
|
| 12 |
+
"batch_size": 64,
|
| 13 |
+
"d_model": 768,
|
| 14 |
+
"dropout": 0.1,
|
| 15 |
+
"dtype": "float32",
|
| 16 |
+
"max_seq_len": 512,
|
| 17 |
+
"model_type": "pico_decoder",
|
| 18 |
+
"n_layers": 14,
|
| 19 |
+
"norm_eps": 1e-05,
|
| 20 |
+
"position_emb_theta": 10000.0,
|
| 21 |
+
"transformers_version": "5.14.1",
|
| 22 |
+
"vocab_size": 50005
|
| 23 |
+
}
|
csp__naive/generation_config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"transformers_version": "5.14.1"
|
| 4 |
+
}
|
csp__naive/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:483feb25e7f8aa800251774159b474f05ee746a874c2a46379b61b8617888819
|
| 3 |
+
size 775260112
|
csp__naive/pico_decoder.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pico Decoder: A Lightweight Causal Transformer Language Model
|
| 3 |
+
Implementation from https://github.com/pico-lm/pico-train/blob/main/src/model/pico_decoder.py
|
| 4 |
+
|
| 5 |
+
Key features:
|
| 6 |
+
- RMSNorm for layer normalization
|
| 7 |
+
- Rotary Positional Embeddings (RoPE)
|
| 8 |
+
- Multi-head attention with KV-cache support
|
| 9 |
+
- SwiGLU activation function
|
| 10 |
+
- Residual connections throughout
|
| 11 |
+
- KV-cache for faster autoregressive generation
|
| 12 |
+
|
| 13 |
+
References:
|
| 14 |
+
- RoPE: https://arxiv.org/abs/2104.09864
|
| 15 |
+
- SwiGLU: https://arxiv.org/abs/2002.05202
|
| 16 |
+
- LLAMA: https://arxiv.org/abs/2302.13971
|
| 17 |
+
|
| 18 |
+
HuggingFace compatibility notes
|
| 19 |
+
---------------------------------
|
| 20 |
+
PicoDecoderHF stores weights at the TOP LEVEL (embedding_proj, layers,
|
| 21 |
+
output_norm, de_embedding_proj) so that state dict keys match the raw
|
| 22 |
+
PicoDecoder checkpoint format exactly. Do NOT add a self.pico_decoder
|
| 23 |
+
wrapper — it would prepend a key prefix that does not exist in any saved
|
| 24 |
+
checkpoint, causing every weight to be MISSING on load.
|
| 25 |
+
|
| 26 |
+
vocab_size in config.json must be the BASE BPE vocabulary size
|
| 27 |
+
(tokenizer.vocab_size), NOT the padded len(tokenizer) which includes
|
| 28 |
+
<unusedN> padding tokens. The embedding table was built with the base size.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from dataclasses import asdict, is_dataclass
|
| 32 |
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
|
| 33 |
+
import torch
|
| 34 |
+
import torch.nn as nn
|
| 35 |
+
import torch.nn.functional as F
|
| 36 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 37 |
+
from transformers import GenerationMixin, PretrainedConfig, PreTrainedModel
|
| 38 |
+
from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
|
| 39 |
+
try:
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from src.config import ModelConfig
|
| 42 |
+
except ImportError:
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class RMSNorm(torch.nn.Module):
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.eps = config.norm_eps
|
| 50 |
+
self.weight = nn.Parameter(torch.ones(config.d_model))
|
| 51 |
+
def _norm(self, x):
|
| 52 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
return self._norm(x.float()).type_as(x) * self.weight
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class RoPE(nn.Module):
|
| 58 |
+
"""
|
| 59 |
+
Rotary Position Embedding.
|
| 60 |
+
freqs_cis is computed lazily on first use and cached per-device,
|
| 61 |
+
avoiding meta-tensor issues when HF loads with low_cpu_mem_usage=True.
|
| 62 |
+
The cache auto-extends if a call needs a longer sequence than the
|
| 63 |
+
current cached length (grows geometrically).
|
| 64 |
+
"""
|
| 65 |
+
def __init__(self, config):
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.theta = config.position_emb_theta
|
| 68 |
+
self.dim = config.d_model // config.attention_n_heads
|
| 69 |
+
self.max_seq = config.max_seq_len
|
| 70 |
+
# NOT a buffer — plain dict so it never touches the meta device
|
| 71 |
+
self._cache: Dict[torch.device, torch.Tensor] = {}
|
| 72 |
+
self._cache_max_seq: Dict[torch.device, int] = {}
|
| 73 |
+
|
| 74 |
+
def _build_cache(self, device: torch.device, length: int) -> torch.Tensor:
|
| 75 |
+
freqs = 1.0 / (
|
| 76 |
+
self.theta ** (
|
| 77 |
+
torch.arange(0, self.dim, 2, device=device).float() / self.dim
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
t = torch.arange(length, device=device)
|
| 81 |
+
freqs = torch.outer(t, freqs)
|
| 82 |
+
return torch.polar(torch.ones_like(freqs), freqs)
|
| 83 |
+
|
| 84 |
+
def _get_freqs_cis(self, device: torch.device, min_length: int = 0) -> torch.Tensor:
|
| 85 |
+
cached_len = self._cache_max_seq.get(device, 0)
|
| 86 |
+
needed = max(min_length, self.max_seq)
|
| 87 |
+
if device not in self._cache or cached_len < needed:
|
| 88 |
+
new_len = max(needed, cached_len * 2)
|
| 89 |
+
self._cache[device] = self._build_cache(device, new_len)
|
| 90 |
+
self._cache_max_seq[device] = new_len
|
| 91 |
+
return self._cache[device]
|
| 92 |
+
|
| 93 |
+
def get_freqs_cis(self, input_shape, start_pos, end_pos, device):
|
| 94 |
+
_f = self._get_freqs_cis(device, min_length=end_pos)[start_pos:end_pos]
|
| 95 |
+
ndim = len(input_shape)
|
| 96 |
+
if ndim < 2:
|
| 97 |
+
raise ValueError(
|
| 98 |
+
f"RoPE expects input with ndim >= 2, got shape {tuple(input_shape)}"
|
| 99 |
+
)
|
| 100 |
+
expected = (input_shape[1], input_shape[-1])
|
| 101 |
+
if tuple(_f.shape) != expected:
|
| 102 |
+
raise ValueError(
|
| 103 |
+
f"RoPE freqs_cis shape mismatch: got {tuple(_f.shape)}, "
|
| 104 |
+
f"expected {expected} (input_shape={tuple(input_shape)}, "
|
| 105 |
+
f"start_pos={start_pos}, end_pos={end_pos}, "
|
| 106 |
+
f"cached_max_seq={self._cache_max_seq.get(device)}, dim={self.dim})"
|
| 107 |
+
)
|
| 108 |
+
return _f.view(*[d if i == 1 or i == ndim - 1 else 1
|
| 109 |
+
for i, d in enumerate(input_shape)])
|
| 110 |
+
|
| 111 |
+
def forward(self, queries, keys, start_pos=0):
|
| 112 |
+
device = queries.device
|
| 113 |
+
q_ = torch.view_as_complex(queries.float().reshape(*queries.shape[:-1], -1, 2))
|
| 114 |
+
k_ = torch.view_as_complex(keys.float().reshape(*keys.shape[:-1], -1, 2))
|
| 115 |
+
fc = self.get_freqs_cis(q_.shape, start_pos, start_pos + q_.shape[1], device)
|
| 116 |
+
return (torch.view_as_real(q_ * fc).flatten(3).type_as(queries),
|
| 117 |
+
torch.view_as_real(k_ * fc).flatten(3).type_as(keys))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Attention(nn.Module):
|
| 121 |
+
def __init__(self, config):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.n_heads = config.attention_n_heads
|
| 124 |
+
self.n_kv_heads = config.attention_n_kv_heads
|
| 125 |
+
self.batch_size = config.batch_size
|
| 126 |
+
self.max_seq_len = config.max_seq_len
|
| 127 |
+
d = config.d_model
|
| 128 |
+
self.head_dim = d // self.n_heads
|
| 129 |
+
self.n_rep = self.n_heads // self.n_kv_heads
|
| 130 |
+
self.q_proj = nn.Linear(d, self.n_heads * self.head_dim, bias=False)
|
| 131 |
+
self.k_proj = nn.Linear(d, self.n_kv_heads * self.head_dim, bias=False)
|
| 132 |
+
self.v_proj = nn.Linear(d, self.n_kv_heads * self.head_dim, bias=False)
|
| 133 |
+
self.o_proj = nn.Linear(self.n_heads * self.head_dim, d, bias=False)
|
| 134 |
+
self.rope = RoPE(config)
|
| 135 |
+
def forward(self, input, mask=None, past_key_values=None, use_cache=False):
|
| 136 |
+
bsz, seq_len, _ = input.shape
|
| 137 |
+
queries = self.q_proj(input).view(bsz, seq_len, self.n_heads, self.head_dim)
|
| 138 |
+
keys = self.k_proj(input).view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
| 139 |
+
values = self.v_proj(input).view(bsz, seq_len, self.n_kv_heads, self.head_dim)
|
| 140 |
+
start_pos = past_key_values[0].shape[1] if past_key_values is not None else 0
|
| 141 |
+
queries, keys = self.rope(queries, keys, start_pos)
|
| 142 |
+
if past_key_values is not None:
|
| 143 |
+
keys = torch.cat([past_key_values[0], keys], dim=1)
|
| 144 |
+
values = torch.cat([past_key_values[1], values], dim=1)
|
| 145 |
+
cached_keys = keys if use_cache else None
|
| 146 |
+
cached_values = values if use_cache else None
|
| 147 |
+
queries = queries.transpose(1, 2)
|
| 148 |
+
keys = keys.transpose(1, 2)
|
| 149 |
+
values = values.transpose(1, 2)
|
| 150 |
+
apply_gqa = self.n_rep > 1
|
| 151 |
+
if apply_gqa and queries.device.type == "mps":
|
| 152 |
+
keys = keys.repeat_interleave(self.n_rep, dim=-3)
|
| 153 |
+
values = values.repeat_interleave(self.n_rep, dim=-3)
|
| 154 |
+
apply_gqa = False
|
| 155 |
+
attn_mask = mask.to(queries.dtype) if mask is not None else None
|
| 156 |
+
with sdpa_kernel(backends=[SDPBackend.CUDNN_ATTENTION, SDPBackend.MATH]):
|
| 157 |
+
attn_output = F.scaled_dot_product_attention(
|
| 158 |
+
queries.contiguous(), keys.contiguous(), values.contiguous(),
|
| 159 |
+
attn_mask=attn_mask, enable_gqa=apply_gqa,
|
| 160 |
+
)
|
| 161 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
| 162 |
+
return self.o_proj(attn_output), (cached_keys, cached_values)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class SwiGLU(nn.Module):
|
| 166 |
+
def __init__(self, config):
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.w_0 = nn.Linear(config.d_model, config.activation_hidden_dim, bias=False)
|
| 169 |
+
self.w_1 = nn.Linear(config.d_model, config.activation_hidden_dim, bias=False)
|
| 170 |
+
self.w_2 = nn.Linear(config.activation_hidden_dim, config.d_model, bias=False)
|
| 171 |
+
def forward(self, x):
|
| 172 |
+
return self.w_2(F.silu(self.w_0(x)) * self.w_1(x))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class PicoDecoderBlock(nn.Module):
|
| 176 |
+
def __init__(self, config):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.attention = Attention(config)
|
| 179 |
+
self.swiglu = SwiGLU(config)
|
| 180 |
+
self.attention_norm = RMSNorm(config)
|
| 181 |
+
self.swiglu_norm = RMSNorm(config)
|
| 182 |
+
def forward(self, input, mask=None, past_key_values=None, use_cache=False):
|
| 183 |
+
attention_output, cached_key_values = self.attention(
|
| 184 |
+
self.attention_norm(input), mask=mask,
|
| 185 |
+
past_key_values=past_key_values, use_cache=use_cache)
|
| 186 |
+
h = input + attention_output
|
| 187 |
+
return h + self.swiglu(self.swiglu_norm(h)), cached_key_values
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class PicoDecoder(nn.Module):
|
| 191 |
+
def __init__(self, model_config):
|
| 192 |
+
super().__init__()
|
| 193 |
+
self.config = model_config
|
| 194 |
+
self.embedding_proj = nn.Embedding(model_config.vocab_size, model_config.d_model)
|
| 195 |
+
self.layers = nn.ModuleList(
|
| 196 |
+
[PicoDecoderBlock(model_config) for _ in range(model_config.n_layers)])
|
| 197 |
+
self.output_norm = RMSNorm(model_config)
|
| 198 |
+
self.de_embedding_proj = nn.Linear(
|
| 199 |
+
model_config.d_model, model_config.vocab_size, bias=False)
|
| 200 |
+
def convert_to_hf_model(self):
|
| 201 |
+
hf = PicoDecoderHF(PicoDecoderHFConfig.from_dataclass(self.config))
|
| 202 |
+
hf.load_state_dict(self.state_dict())
|
| 203 |
+
return hf
|
| 204 |
+
def forward(self, input_ids, past_key_values=None, use_cache=False):
|
| 205 |
+
seq_len = input_ids.shape[-1]
|
| 206 |
+
h = self.embedding_proj(input_ids)
|
| 207 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
| 208 |
+
mask = None
|
| 209 |
+
if seq_len > 1:
|
| 210 |
+
mask = torch.full((seq_len, seq_len), float("-inf"))
|
| 211 |
+
mask = torch.triu(mask, diagonal=1)
|
| 212 |
+
if past_key_values is not None:
|
| 213 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos)), mask])
|
| 214 |
+
mask = mask.to(h.device)
|
| 215 |
+
cached_key_values = () if use_cache else None
|
| 216 |
+
for idx, layer in enumerate(self.layers):
|
| 217 |
+
layer_past = past_key_values[idx] if past_key_values is not None else None
|
| 218 |
+
h, layer_cached = layer(
|
| 219 |
+
h, mask=mask, past_key_values=layer_past, use_cache=use_cache)
|
| 220 |
+
if use_cache:
|
| 221 |
+
cached_key_values += (layer_cached,)
|
| 222 |
+
return self.de_embedding_proj(self.output_norm(h)).float(), cached_key_values
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class PicoDecoderHFConfig(PretrainedConfig):
|
| 226 |
+
model_type = "pico_decoder"
|
| 227 |
+
def __init__(self,
|
| 228 |
+
n_layers=14, d_model=768, vocab_size=32768,
|
| 229 |
+
attention_n_heads=12, attention_n_kv_heads=1,
|
| 230 |
+
max_seq_len=512, batch_size=64, position_emb_theta=10000.0,
|
| 231 |
+
activation_hidden_dim=3072, norm_eps=1e-5, dropout=0.1,
|
| 232 |
+
**kwargs):
|
| 233 |
+
if not attention_n_kv_heads:
|
| 234 |
+
attention_n_kv_heads = attention_n_heads
|
| 235 |
+
super().__init__(**kwargs)
|
| 236 |
+
self.n_layers = n_layers
|
| 237 |
+
self.d_model = d_model
|
| 238 |
+
self.vocab_size = vocab_size
|
| 239 |
+
self.attention_n_heads = attention_n_heads
|
| 240 |
+
self.attention_n_kv_heads = attention_n_kv_heads
|
| 241 |
+
self.max_seq_len = max_seq_len
|
| 242 |
+
self.batch_size = batch_size
|
| 243 |
+
self.position_emb_theta = position_emb_theta
|
| 244 |
+
self.activation_hidden_dim = activation_hidden_dim
|
| 245 |
+
self.norm_eps = norm_eps
|
| 246 |
+
self.dropout = dropout
|
| 247 |
+
@classmethod
|
| 248 |
+
def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PicoDecoderHFConfig":
|
| 249 |
+
pico_config = cls(**config_dict)
|
| 250 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
| 251 |
+
unused_kwargs = {k: v for k, v in kwargs.items() if not hasattr(pico_config, k)}
|
| 252 |
+
if return_unused_kwargs:
|
| 253 |
+
return pico_config, unused_kwargs
|
| 254 |
+
return pico_config
|
| 255 |
+
@classmethod
|
| 256 |
+
def from_dataclass(cls, model_config):
|
| 257 |
+
if is_dataclass(model_config) and not isinstance(model_config, type):
|
| 258 |
+
d = asdict(model_config)
|
| 259 |
+
elif isinstance(model_config, dict):
|
| 260 |
+
d = dict(model_config)
|
| 261 |
+
elif hasattr(model_config, "__dict__"):
|
| 262 |
+
d = dict(vars(model_config))
|
| 263 |
+
else:
|
| 264 |
+
raise TypeError(
|
| 265 |
+
f"Cannot build PicoDecoderHFConfig from {type(model_config).__name__}"
|
| 266 |
+
)
|
| 267 |
+
return cls.from_dict(d)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class PicoDecoderHF(PreTrainedModel, GenerationMixin):
|
| 271 |
+
"""
|
| 272 |
+
HuggingFace wrapper for BeetleLM PicoDecoder.
|
| 273 |
+
Usage: AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True)
|
| 274 |
+
Works with CPU, CUDA (A100, etc.), and MPS out of the box.
|
| 275 |
+
"""
|
| 276 |
+
config_class = PicoDecoderHFConfig
|
| 277 |
+
_no_split_modules = ["PicoDecoderBlock"]
|
| 278 |
+
_tied_weights_keys = []
|
| 279 |
+
|
| 280 |
+
def __init__(self, config: PicoDecoderHFConfig):
|
| 281 |
+
super().__init__(config)
|
| 282 |
+
self.embedding_proj = nn.Embedding(config.vocab_size, config.d_model)
|
| 283 |
+
self.layers = nn.ModuleList(
|
| 284 |
+
[PicoDecoderBlock(config) for _ in range(config.n_layers)])
|
| 285 |
+
self.output_norm = RMSNorm(config)
|
| 286 |
+
self.de_embedding_proj = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 287 |
+
# Required: lets HF finalize weight init and meta-device materialization
|
| 288 |
+
self.post_init()
|
| 289 |
+
|
| 290 |
+
# Required for low_cpu_mem_usage / Accelerate device-dispatch to work
|
| 291 |
+
def _init_weights(self, module):
|
| 292 |
+
if isinstance(module, nn.Linear):
|
| 293 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 294 |
+
if module.bias is not None:
|
| 295 |
+
nn.init.zeros_(module.bias)
|
| 296 |
+
elif isinstance(module, nn.Embedding):
|
| 297 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 298 |
+
elif isinstance(module, RMSNorm):
|
| 299 |
+
nn.init.ones_(module.weight)
|
| 300 |
+
|
| 301 |
+
def get_input_embeddings(self): return self.embedding_proj
|
| 302 |
+
def set_input_embeddings(self, value): self.embedding_proj = value
|
| 303 |
+
|
| 304 |
+
def forward(self, input_ids=None, past_key_values=None,
|
| 305 |
+
use_cache=False, labels=None, **kwargs):
|
| 306 |
+
seq_len = input_ids.shape[-1]
|
| 307 |
+
h = self.embedding_proj(input_ids)
|
| 308 |
+
start_pos = 0 if past_key_values is None else past_key_values[0][0].shape[1]
|
| 309 |
+
mask = None
|
| 310 |
+
if seq_len > 1:
|
| 311 |
+
mask = torch.full((seq_len, seq_len), float("-inf"), device=h.device)
|
| 312 |
+
mask = torch.triu(mask, diagonal=1)
|
| 313 |
+
if past_key_values is not None:
|
| 314 |
+
mask = torch.hstack([torch.zeros((seq_len, start_pos), device=h.device), mask])
|
| 315 |
+
cached_key_values = () if use_cache else None
|
| 316 |
+
for idx, layer in enumerate(self.layers):
|
| 317 |
+
layer_past = past_key_values[idx] if past_key_values is not None else None
|
| 318 |
+
h, layer_cached = layer(
|
| 319 |
+
h, mask=mask, past_key_values=layer_past, use_cache=use_cache)
|
| 320 |
+
if use_cache:
|
| 321 |
+
cached_key_values += (layer_cached,)
|
| 322 |
+
logits = self.de_embedding_proj(self.output_norm(h)).float()
|
| 323 |
+
loss = None
|
| 324 |
+
if labels is not None:
|
| 325 |
+
loss = F.cross_entropy(
|
| 326 |
+
logits[:, :-1].contiguous().view(-1, self.config.vocab_size),
|
| 327 |
+
labels[:, 1:].contiguous().clamp(0, self.config.vocab_size - 1).view(-1),
|
| 328 |
+
)
|
| 329 |
+
if use_cache:
|
| 330 |
+
return CausalLMOutputWithPast(
|
| 331 |
+
loss=loss, logits=logits, past_key_values=cached_key_values)
|
| 332 |
+
return CausalLMOutput(loss=loss, logits=logits)
|
| 333 |
+
|
| 334 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
| 335 |
+
return {"input_ids": input_ids,
|
| 336 |
+
"past_key_values": past_key_values,
|
| 337 |
+
"use_cache": True}
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
PicoDecoderHFConfig.register_for_auto_class()
|
| 341 |
+
PicoDecoderHF.register_for_auto_class("AutoModel")
|
| 342 |
+
PicoDecoderHF.register_for_auto_class("AutoModelForCausalLM")
|
csp__naive/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
csp__naive/tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"clean_up_tokenization_spaces": false,
|
| 4 |
+
"cls_token": "[CLS]",
|
| 5 |
+
"is_local": false,
|
| 6 |
+
"local_files_only": false,
|
| 7 |
+
"mask_token": "[MASK]",
|
| 8 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 9 |
+
"pad_token": "[PAD]",
|
| 10 |
+
"sep_token": "[SEP]",
|
| 11 |
+
"tokenizer_class": "TokenizersBackend",
|
| 12 |
+
"unk_token": "[UNK]"
|
| 13 |
+
}
|