Maxilicious20 commited on
Commit
30eae08
·
verified ·
1 Parent(s): 1b03d77

Publish Velqora-38M-Instruct (safetensors, best/latest checkpoints, tokenizer, and inference script)

Browse files
README.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ pipeline_tag: text-generation
5
+ datasets:
6
+ - HuggingFaceTB/cosmopedia-100k
7
+ - HuggingFaceFW/fineweb-edu
8
+ - roneneldan/TinyStories
9
+ - HuggingFaceTB/smoltalk
10
+ - HuggingFaceH4/ultrachat_200k
11
+ - HuggingFaceH4/no_robots
12
+ tags:
13
+ - velqora
14
+ - from-scratch
15
+ - causal-language-model
16
+ - custom-architecture
17
+ - pytorch
18
+ - grouped-query-attention
19
+ - qk-norm
20
+ - value-residuals
21
+ - research
22
+ license: apache-2.0
23
+ ---
24
+
25
+ # Velqora-38M-Instruct
26
+
27
+ **Velqora-38M-Instruct** is a **38,025,227-parameter** (~38.03M), English-first, decoder-only instruction-tuned conversational language model **trained from random initialization** on a single **NVIDIA GeForce RTX 4060 (8 GB)** under Windows 11.
28
+
29
+ **GGUF companion:** [Maxilicious20/Velqora-38M-Instruct-GGUF](https://huggingface.co/Maxilicious20/Velqora-38M-Instruct-GGUF)
30
+
31
+ ## Model overview
32
+
33
+ | Property | Value |
34
+ |---|---|
35
+ | Developer | [Maxilicious20](https://huggingface.co/Maxilicious20) |
36
+ | Parameters | **38,025,227** (~38.03M) |
37
+ | Model type | Decoder-only causal language model (Instruct / SFT) |
38
+ | Training origin | **From scratch**, no pretrained foundation weights |
39
+ | Primary language | **English** |
40
+ | Transformer layers | 12 |
41
+ | Hidden size | 512 |
42
+ | Attention | 8 query heads / 2 key-value heads (GQA) + QK-Norm + Layer-0 Value Residuals |
43
+ | Feed-forward dimension | 1,408, SwiGLU |
44
+ | Position embeddings | RoPE, base θ = 10,000 |
45
+ | Normalization | RMSNorm |
46
+ | Token embeddings | Tied input/output embeddings |
47
+ | Tokenizer | Custom 8,192-token byte-level BPE |
48
+ | Maximum context window | **1,024 tokens** |
49
+ | Best validation loss | `1.4712` |
50
+ | Implementation | Custom PyTorch (`scaled_dot_product_attention`, `bfloat16`) |
51
+ | Training hardware | Windows 11, NVIDIA RTX 4060 8 GB |
52
+ | License | **Apache-2.0** |
53
+
54
+ > **Implementation note:** This release uses a custom PyTorch architecture (`velqora/model.py`), custom tokenizer (`tokenizer.json`), and tied embeddings rather than `AutoModelForCausalLM`.
55
+
56
+ ## Training
57
+
58
+ This checkpoint was trained from random initialization in two stages on a single NVIDIA RTX 4060 (8 GB):
59
+
60
+ 1. **Curriculum Pretraining:** Next-token prediction across `HuggingFaceTB/cosmopedia-100k`, `HuggingFaceFW/fineweb-edu`, and `roneneldan/TinyStories`, scaling context length progressively up to the full maximum window.
61
+ 2. **Supervised Fine-Tuning (SFT):** Assistant-only loss-masked multi-turn ChatML fine-tuning across `HuggingFaceTB/smoltalk`, `HuggingFaceH4/ultrachat_200k`, `HuggingFaceH4/no_robots`, and multi-turn recall/grounding dialogues.
62
+
63
+ ## Download and run (custom PyTorch implementation)
64
+
65
+ Repository layout:
66
+
67
+ ```text
68
+ README.md
69
+ model.safetensors # Exported bfloat16 weights (best checkpoint)
70
+ config.json # Velqora architecture configuration
71
+ tokenizer.json # Custom 8,192-token byte-level BPE tokenizer
72
+ generation_config.json # Recommended generation defaults
73
+ run_inference.py # Ready-to-run CLI inference script
74
+ ├── best_checkpoint/
75
+ │ └── model.pt # Best validation PyTorch checkpoint
76
+ velqora/
77
+ __init__.py
78
+ model.py # Custom VelqoraForCausalLM implementation
79
+ ```
80
+
81
+ Install dependencies and run locally:
82
+
83
+ ```bash
84
+ pip install torch safetensors tokenizers huggingface_hub
85
+ hf download Maxilicious20/Velqora-38M-Instruct --local-dir ./Velqora-38M-Instruct
86
+ python ./Velqora-38M-Instruct/run_inference.py --model-dir ./Velqora-38M-Instruct --prompt "What is the capital of Germany?"
87
+ ```
88
+
89
+ ### Chat serialization
90
+
91
+ This instruct checkpoint uses ChatML role formatting:
92
+
93
+ ```text
94
+ <|im_start|>system
95
+ You are Velqora, a helpful, thoughtful, and friendly AI assistant.<|im_end|>
96
+ <|im_start|>user
97
+ Hello!<|im_end|>
98
+ <|im_start|>assistant
99
+ ```
100
+
101
+ Assistant turns terminate with `<|im_end|>` (or `<|endoftext|>`). Recommended generation settings: temperature **0.35–0.55**, top-p **0.88**, repetition penalty **1.12**, and max context **1,024 tokens**.
102
+
103
+ ## Intended use and limitations
104
+
105
+ **Appropriate use:** Research on ultra-small, from-scratch language models, local edge inference experiments, and educational study of modern transformer components (GQA, QK-Norm, Value Residuals, SwiGLU, RoPE).
106
+
107
+ **Limitations:** Because this model has ~38M parameters trained from scratch on a single consumer GPU, it can hallucinate facts, make arithmetic errors, or struggle with complex instructions. Do not use it for medical, legal, financial, or safety-critical tasks.
108
+
109
+ ## License
110
+
111
+ Licensed under the **Apache License 2.0** (`apache-2.0`).
112
+
113
+ ## Citation and links
114
+
115
+ - **PyTorch Model:** [Maxilicious20/Velqora-38M-Instruct](https://huggingface.co/Maxilicious20/Velqora-38M-Instruct)
116
+ - **GGUF Companion:** [Maxilicious20/Velqora-38M-Instruct-GGUF](https://huggingface.co/Maxilicious20/Velqora-38M-Instruct-GGUF)
best_checkpoint/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f5fd7a81a2e619e777fd1fe332cdd20e2fe2be4fa9aa021b8cc26934e5ed755
3
+ size 152156588
config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "Velqora-38M-Instruct",
3
+ "vocab_size": 8192,
4
+ "d_model": 512,
5
+ "n_layers": 12,
6
+ "n_heads": 8,
7
+ "n_kv_heads": 2,
8
+ "d_ff": 1408,
9
+ "max_seq_len": 1024,
10
+ "rope_theta": 10000.0,
11
+ "dropout": 0.0,
12
+ "tie_embeddings": true,
13
+ "architectures": [
14
+ "VelqoraForCausalLM"
15
+ ],
16
+ "model_type": "velqora",
17
+ "torch_dtype": "bfloat16"
18
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "max_new_tokens": 256,
3
+ "temperature": 0.45,
4
+ "top_p": 0.88,
5
+ "repetition_penalty": 1.12,
6
+ "no_repeat_ngram_size": 3,
7
+ "pad_token_id": 0,
8
+ "bos_token_id": 2,
9
+ "eos_token_id": 3
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6641cd0a7b4305d9a95cbd0c95d91cd88f5f17dba6e6616b712edf2795d6198
3
+ size 76064694
run_inference.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+ import torch
5
+ from safetensors.torch import load_file
6
+ from tokenizers import Tokenizer
7
+ from velqora.model import VelqoraConfig, VelqoraForCausalLM
8
+
9
+
10
+ def load_model(model_dir: str, device: torch.device):
11
+ with open(os.path.join(model_dir, "config.json"), "r", encoding="utf-8") as f:
12
+ cfg_raw = json.load(f)
13
+ valid_keys = VelqoraConfig.__dataclass_fields__.keys()
14
+ cfg = VelqoraConfig(**{k: v for k, v in cfg_raw.items() if k in valid_keys})
15
+
16
+ model = VelqoraForCausalLM(cfg).to(device)
17
+ st_path = os.path.join(model_dir, "model.safetensors")
18
+ state = load_file(st_path, device=str(device))
19
+ if cfg.tie_embeddings and "lm_head.weight" not in state:
20
+ state["lm_head.weight"] = state["embed_tokens.weight"]
21
+ model.load_state_dict(state)
22
+ model.eval()
23
+
24
+ tok = Tokenizer.from_file(os.path.join(model_dir, "tokenizer.json"))
25
+ return model, tok, cfg
26
+
27
+
28
+ def main():
29
+ parser = argparse.ArgumentParser(description="Run local inference with Velqora")
30
+ parser.add_argument("--model-dir", type=str, default=os.path.dirname(os.path.abspath(__file__)))
31
+ parser.add_argument("--prompt", type=str, default=None)
32
+ parser.add_argument("--temperature", type=float, default=0.45)
33
+ parser.add_argument("--top-p", type=float, default=0.88)
34
+ parser.add_argument("--max-new-tokens", type=int, default=160)
35
+ args = parser.parse_args()
36
+
37
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
38
+ model, tok, cfg = load_model(args.model_dir, device)
39
+ is_instruct = "instruct" in cfg.model_name.lower()
40
+
41
+ stop_ids = [tok.token_to_id("<|im_end|>"), tok.token_to_id("<|endoftext|>")]
42
+ stop_ids = [i for i in stop_ids if i is not None]
43
+
44
+ def run_once(text: str):
45
+ if is_instruct:
46
+ formatted = (
47
+ "<|im_start|>system\nYou are Velqora, a helpful, thoughtful, and friendly AI assistant.<|im_end|>\n"
48
+ f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n"
49
+ )
50
+ else:
51
+ formatted = text
52
+ ids = torch.tensor([tok.encode(formatted).ids], dtype=torch.long, device=device)
53
+ out = model.generate(
54
+ ids,
55
+ max_new_tokens=args.max_new_tokens,
56
+ temperature=args.temperature,
57
+ top_p=args.top_p,
58
+ stop_token_ids=stop_ids,
59
+ )[0].tolist()
60
+ reply = tok.decode(out[ids.shape[1] :], skip_special_tokens=True).strip()
61
+ print(reply)
62
+
63
+ if args.prompt is not None:
64
+ run_once(args.prompt)
65
+ return
66
+
67
+ print(f"Loaded {cfg.model_name} on {device}. Type /quit to exit.")
68
+ while True:
69
+ user_in = input("\nPrompt: ").strip()
70
+ if not user_in:
71
+ continue
72
+ if user_in.lower() in {"/quit", "/exit"}:
73
+ break
74
+ run_once(user_in)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
velqora/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import VelqoraConfig, VelqoraForCausalLM
velqora/model.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ @dataclass
9
+ class VelqoraConfig:
10
+ model_name: str = "Velqora-40M"
11
+ vocab_size: int = 8192
12
+ d_model: int = 512
13
+ n_layers: int = 12
14
+ n_heads: int = 8
15
+ n_kv_heads: int = 4
16
+ d_ff: int = 1536
17
+ max_seq_len: int = 2048
18
+ rope_theta: float = 30000.0
19
+ dropout: float = 0.0
20
+ tie_embeddings: bool = True
21
+
22
+
23
+ class RMSNorm(nn.Module):
24
+ def __init__(self, dim: int, eps: float = 1e-6):
25
+ super().__init__()
26
+ self.eps = eps
27
+ self.weight = nn.Parameter(torch.ones(dim))
28
+
29
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
30
+ norm = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
31
+ return norm * self.weight
32
+
33
+
34
+ def precompute_rope_freqs(head_dim: int, max_seq_len: int, theta: float = 30000.0, device=None):
35
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
36
+ t = torch.arange(max_seq_len, device=device).float()
37
+ freqs = torch.outer(t, inv_freq)
38
+ return torch.cos(freqs), torch.sin(freqs)
39
+
40
+
41
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
42
+ B, H, T, D = x.shape
43
+ x1 = x[..., : D // 2]
44
+ x2 = x[..., D // 2 :]
45
+ cos = cos[:T].unsqueeze(0).unsqueeze(0)
46
+ sin = sin[:T].unsqueeze(0).unsqueeze(0)
47
+ out = torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
48
+ return out.to(x.dtype)
49
+
50
+
51
+ class GroupedQueryAttention(nn.Module):
52
+ def __init__(self, cfg: VelqoraConfig, layer_idx: int):
53
+ super().__init__()
54
+ self.layer_idx = layer_idx
55
+ self.n_heads = cfg.n_heads
56
+ self.n_kv_heads = cfg.n_kv_heads
57
+ self.n_rep = cfg.n_heads // cfg.n_kv_heads
58
+ self.head_dim = cfg.d_model // cfg.n_heads
59
+
60
+ self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)
61
+ self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
62
+ self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
63
+ self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)
64
+
65
+ self.q_norm = RMSNorm(self.head_dim)
66
+ self.k_norm = RMSNorm(self.head_dim)
67
+
68
+ if layer_idx > 0:
69
+ self.v_res_alpha = nn.Parameter(torch.zeros(1))
70
+
71
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, v0: torch.Tensor | None = None):
72
+ B, T, C = x.shape
73
+ q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
74
+ k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
75
+ v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
76
+
77
+ if self.layer_idx == 0:
78
+ v0 = v
79
+ elif v0 is not None:
80
+ v = v + self.v_res_alpha.to(v.dtype) * v0
81
+
82
+ q = apply_rope(self.q_norm(q), cos, sin)
83
+ k = apply_rope(self.k_norm(k), cos, sin)
84
+
85
+ if self.n_rep > 1:
86
+ k = k.repeat_interleave(self.n_rep, dim=1)
87
+ v = v.repeat_interleave(self.n_rep, dim=1)
88
+
89
+ attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
90
+ attn_out = attn_out.transpose(1, 2).contiguous().view(B, T, C)
91
+ return self.o_proj(attn_out), v0
92
+
93
+
94
+ class SwiGLU(nn.Module):
95
+ def __init__(self, cfg: VelqoraConfig):
96
+ super().__init__()
97
+ self.gate_proj = nn.Linear(cfg.d_model, cfg.d_ff, bias=False)
98
+ self.up_proj = nn.Linear(cfg.d_model, cfg.d_ff, bias=False)
99
+ self.down_proj = nn.Linear(cfg.d_ff, cfg.d_model, bias=False)
100
+
101
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
102
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
103
+
104
+
105
+ class VelqoraBlock(nn.Module):
106
+ def __init__(self, cfg: VelqoraConfig, layer_idx: int):
107
+ super().__init__()
108
+ self.attn_norm = RMSNorm(cfg.d_model)
109
+ self.attn = GroupedQueryAttention(cfg, layer_idx)
110
+ self.ffn_norm = RMSNorm(cfg.d_model)
111
+ self.ffn = SwiGLU(cfg)
112
+
113
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, v0: torch.Tensor | None = None):
114
+ h, v0 = self.attn(self.attn_norm(x), cos, sin, v0=v0)
115
+ x = x + h
116
+ x = x + self.ffn(self.ffn_norm(x))
117
+ return x, v0
118
+
119
+
120
+ class VelqoraForCausalLM(nn.Module):
121
+ def __init__(self, cfg: VelqoraConfig):
122
+ super().__init__()
123
+ self.cfg = cfg
124
+ self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.d_model)
125
+ self.layers = nn.ModuleList([VelqoraBlock(cfg, i) for i in range(cfg.n_layers)])
126
+ self.norm = RMSNorm(cfg.d_model)
127
+ self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
128
+
129
+ if cfg.tie_embeddings:
130
+ self.lm_head.weight = self.embed_tokens.weight
131
+
132
+ head_dim = cfg.d_model // cfg.n_heads
133
+ cos, sin = precompute_rope_freqs(head_dim, cfg.max_seq_len, cfg.rope_theta)
134
+ self.register_buffer("rope_cos", cos, persistent=False)
135
+ self.register_buffer("rope_sin", sin, persistent=False)
136
+
137
+ def count_parameters(self) -> int:
138
+ return sum(p.numel() for p in self.parameters())
139
+
140
+ def forward(self, input_ids: torch.Tensor, labels: torch.Tensor | None = None):
141
+ B, T = input_ids.shape
142
+ if T > self.cfg.max_seq_len:
143
+ input_ids = input_ids[:, -self.cfg.max_seq_len :]
144
+ if labels is not None:
145
+ labels = labels[:, -self.cfg.max_seq_len :]
146
+ T = self.cfg.max_seq_len
147
+
148
+ x = self.embed_tokens(input_ids)
149
+ v0 = None
150
+ for layer in self.layers:
151
+ x, v0 = layer(x, self.rope_cos, self.rope_sin, v0=v0)
152
+
153
+ logits = self.lm_head(self.norm(x))
154
+ loss = None
155
+ if labels is not None:
156
+ shift_logits = logits[:, :-1, :].contiguous()
157
+ shift_labels = labels[:, 1:].contiguous()
158
+ loss = F.cross_entropy(
159
+ shift_logits.view(-1, self.cfg.vocab_size),
160
+ shift_labels.view(-1),
161
+ ignore_index=-100,
162
+ )
163
+ return logits, loss
164
+
165
+ @torch.no_grad()
166
+ def generate(
167
+ self,
168
+ input_ids: torch.Tensor,
169
+ max_new_tokens: int = 256,
170
+ temperature: float = 0.45,
171
+ top_p: float = 0.88,
172
+ repetition_penalty: float = 1.12,
173
+ no_repeat_ngram_size: int = 3,
174
+ stop_token_ids: list[int] | None = None,
175
+ ) -> torch.Tensor:
176
+ self.eval()
177
+ stop_set = set(stop_token_ids or [])
178
+ prompt_len = input_ids.shape[1]
179
+
180
+ for _ in range(max_new_tokens):
181
+ ctx = input_ids[:, -self.cfg.max_seq_len :]
182
+ logits, _ = self(ctx)
183
+ next_logits = logits[:, -1, :].float()
184
+
185
+ generated_ids = input_ids[0, prompt_len:].tolist()
186
+ if repetition_penalty != 1.0 and generated_ids:
187
+ for token_id in set(generated_ids):
188
+ if next_logits[0, token_id] < 0:
189
+ next_logits[0, token_id] *= repetition_penalty
190
+ else:
191
+ next_logits[0, token_id] /= repetition_penalty
192
+
193
+ if no_repeat_ngram_size > 1 and len(generated_ids) >= no_repeat_ngram_size - 1:
194
+ prefix = tuple(generated_ids[-(no_repeat_ngram_size - 1) :])
195
+ for i in range(len(generated_ids) - no_repeat_ngram_size + 1):
196
+ if tuple(generated_ids[i : i + no_repeat_ngram_size - 1]) == prefix:
197
+ next_logits[0, generated_ids[i + no_repeat_ngram_size - 1]] = float("-inf")
198
+
199
+ if temperature <= 0.0:
200
+ next_token = torch.argmax(next_logits, dim=-1, keepdim=True)
201
+ else:
202
+ next_logits = next_logits / temperature
203
+ sorted_logits, sorted_indices = torch.sort(next_logits, descending=True)
204
+ probs = F.softmax(sorted_logits, dim=-1)
205
+ cum_probs = torch.cumsum(probs, dim=-1)
206
+ remove_mask = cum_probs > top_p
207
+ remove_mask[..., 1:] = remove_mask[..., :-1].clone()
208
+ remove_mask[..., 0] = False
209
+ sorted_logits[remove_mask] = float("-inf")
210
+ filtered_probs = F.softmax(sorted_logits, dim=-1)
211
+ sampled_idx = torch.multinomial(filtered_probs, num_samples=1)
212
+ next_token = sorted_indices.gather(-1, sampled_idx)
213
+
214
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
215
+ if next_token.item() in stop_set:
216
+ break
217
+ return input_ids