streamllm 0.1.2__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {streamllm-0.1.2 → streamllm-0.2.0}/PKG-INFO +8 -2
- {streamllm-0.1.2 → streamllm-0.2.0}/README.md +7 -1
- {streamllm-0.1.2 → streamllm-0.2.0}/pyproject.toml +1 -1
- {streamllm-0.1.2 → streamllm-0.2.0}/setup.py +1 -1
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/__init__.py +1 -1
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/auto_model.py +105 -152
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/cli.py +107 -33
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/engine.py +31 -16
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/models.py +23 -9
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/PKG-INFO +8 -2
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/SOURCES.txt +2 -1
- streamllm-0.2.0/tests/test_generation.py +36 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/LICENSE +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/setup.cfg +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/hardware.py +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/kv_cache.py +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/pinned_host.py +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/scratchpad.py +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm/transfer.py +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/dependency_links.txt +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/entry_points.txt +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/requires.txt +0 -0
- {streamllm-0.1.2 → streamllm-0.2.0}/streamllm.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: streamllm
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Run bigger LLMs on smaller GPUs through intelligent, asynchronous layer streaming.
|
|
5
5
|
Author: StreamLLM Authors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -150,7 +150,7 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
150
150
|
- **Static GPU Scratchpad Pool (`GPUScratchpadPool`):** Pre-allocates two static VRAM buffer slots (Slot A and Slot B). Eliminates `cudaMalloc` and `cudaFree` churn during generation.
|
|
151
151
|
- **Dual CUDA Streams:** Dedicated `compute_stream` and `transfer_stream` with lock-free hardware event synchronization (`torch.cuda.Event`).
|
|
152
152
|
- **Pinned Host Memory:** Uses page-locked RAM (`torch.Tensor.pin_memory()`) for true non-blocking PCIe transfers.
|
|
153
|
-
- **KV-Cache Manager:**
|
|
153
|
+
- **KV-Cache Manager:** Generation reserves estimated KV storage for the requested context when choosing GPU-resident layers. Peak usage also depends on the prompt and available device memory.
|
|
154
154
|
|
|
155
155
|
---
|
|
156
156
|
|
|
@@ -168,3 +168,9 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
168
168
|
| **32 Layers** | 2048.2 MB | 278.85 ms | **265.03 ms** | **1.05x** | **128.0 MB** |
|
|
169
169
|
|
|
170
170
|
> **Key Takeaway:** Even as total model weights scale past 2.0 GB, StreamLLM's static scratchpad pool holds physical GPU memory strictly at **128.0 MB** while asynchronous prefetching delivers up to **1.28x faster inference**.
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
### Benchmark a real checkpoint
|
|
174
|
+
|
|
175
|
+
After installing the checkpoint, run `streamllm decode-bench deepseek-1.5b --device cuda:0 --max-tokens 128`.
|
|
176
|
+
The benchmark performs one warmup and five timed greedy runs. It reports time to first token, decode throughput after the first token, and CUDA memory peaks. Use the same prompt and generation limit for comparisons. Chat and one-shot generation default to 1,024 new tokens.
|
|
@@ -133,7 +133,7 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
133
133
|
- **Static GPU Scratchpad Pool (`GPUScratchpadPool`):** Pre-allocates two static VRAM buffer slots (Slot A and Slot B). Eliminates `cudaMalloc` and `cudaFree` churn during generation.
|
|
134
134
|
- **Dual CUDA Streams:** Dedicated `compute_stream` and `transfer_stream` with lock-free hardware event synchronization (`torch.cuda.Event`).
|
|
135
135
|
- **Pinned Host Memory:** Uses page-locked RAM (`torch.Tensor.pin_memory()`) for true non-blocking PCIe transfers.
|
|
136
|
-
- **KV-Cache Manager:**
|
|
136
|
+
- **KV-Cache Manager:** Generation reserves estimated KV storage for the requested context when choosing GPU-resident layers. Peak usage also depends on the prompt and available device memory.
|
|
137
137
|
|
|
138
138
|
---
|
|
139
139
|
|
|
@@ -151,3 +151,9 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
151
151
|
| **32 Layers** | 2048.2 MB | 278.85 ms | **265.03 ms** | **1.05x** | **128.0 MB** |
|
|
152
152
|
|
|
153
153
|
> **Key Takeaway:** Even as total model weights scale past 2.0 GB, StreamLLM's static scratchpad pool holds physical GPU memory strictly at **128.0 MB** while asynchronous prefetching delivers up to **1.28x faster inference**.
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
### Benchmark a real checkpoint
|
|
157
|
+
|
|
158
|
+
After installing the checkpoint, run `streamllm decode-bench deepseek-1.5b --device cuda:0 --max-tokens 128`.
|
|
159
|
+
The benchmark performs one warmup and five timed greedy runs. It reports time to first token, decode throughput after the first token, and CUDA memory peaks. Use the same prompt and generation limit for comparisons. Chat and one-shot generation default to 1,024 new tokens.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "streamllm"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Run bigger LLMs on smaller GPUs through intelligent, asynchronous layer streaming."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -86,49 +86,21 @@ class StreamLLMModel(nn.Module):
|
|
|
86
86
|
self.is_hf_transformer = False
|
|
87
87
|
|
|
88
88
|
if hf_model is not None:
|
|
89
|
-
|
|
90
|
-
if hasattr(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
self.
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
# 3. LM Projection Head
|
|
106
|
-
if hasattr(hf_model, "lm_head") and hf_model.lm_head is not None:
|
|
107
|
-
self.lm_head = hf_model.lm_head.to(device)
|
|
108
|
-
else:
|
|
109
|
-
self.lm_head = nn.Linear(self.hidden_size, self.vocab_size, bias=False).to(device)
|
|
110
|
-
|
|
111
|
-
# 4. Extract transformer layers
|
|
112
|
-
raw_layers = None
|
|
113
|
-
if hasattr(hf_model, "model") and hasattr(hf_model.model, "layers"):
|
|
114
|
-
raw_layers = hf_model.model.layers
|
|
115
|
-
elif hasattr(hf_model, "transformer") and hasattr(hf_model.transformer, "h"):
|
|
116
|
-
raw_layers = hf_model.transformer.h
|
|
117
|
-
|
|
118
|
-
if raw_layers and len(raw_layers) > 0:
|
|
119
|
-
self.num_layers = len(raw_layers)
|
|
120
|
-
self.is_hf_transformer = True
|
|
121
|
-
# Use Layer 0 as the GPU execution scratchpad module template
|
|
122
|
-
self.layer_template = raw_layers[0].to(device)
|
|
123
|
-
|
|
124
|
-
# Register all layer state dicts in pinned host RAM
|
|
125
|
-
self.host_registry = PinnedHostWeightRegistry()
|
|
126
|
-
for i, lyr in enumerate(raw_layers):
|
|
127
|
-
layer_weights = {
|
|
128
|
-
k: v.detach().clone().cpu()
|
|
129
|
-
for k, v in lyr.state_dict().items()
|
|
130
|
-
}
|
|
131
|
-
self.host_registry.register_layer(i, layer_weights, pin=(device.type == "cuda"))
|
|
89
|
+
decoder = getattr(hf_model, "model", None)
|
|
90
|
+
if (decoder is None or not hasattr(decoder, "layers")
|
|
91
|
+
or not hasattr(decoder, "norm") or hf_model.get_output_embeddings() is None):
|
|
92
|
+
raise ValueError(f"Unsupported decoder layout for {config.model_type}")
|
|
93
|
+
self.embed_tokens = hf_model.get_input_embeddings().to(device)
|
|
94
|
+
self.norm = decoder.norm.to(device)
|
|
95
|
+
self.lm_head = hf_model.get_output_embeddings().to(device)
|
|
96
|
+
self.num_layers = len(decoder.layers)
|
|
97
|
+
self.is_hf_transformer = True
|
|
98
|
+
self.layer_template = decoder.layers[0]
|
|
99
|
+
self.host_registry = PinnedHostWeightRegistry()
|
|
100
|
+
for index, layer in enumerate(decoder.layers):
|
|
101
|
+
self.host_registry.register_layer(index, layer.state_dict(), pin=device.type == "cuda")
|
|
102
|
+
decoder.layers[index] = nn.Identity()
|
|
103
|
+
self.layer_template.eval()
|
|
132
104
|
|
|
133
105
|
# Rotary embeddings if available
|
|
134
106
|
self.rotary_emb = None
|
|
@@ -136,10 +108,6 @@ class StreamLLMModel(nn.Module):
|
|
|
136
108
|
self.rotary_emb = hf_model.model.rotary_emb.to(device)
|
|
137
109
|
elif hasattr(hf_model, "rotary_emb"):
|
|
138
110
|
self.rotary_emb = hf_model.rotary_emb.to(device)
|
|
139
|
-
else:
|
|
140
|
-
self.layer_template = self._create_layer_template(self.hidden_size)
|
|
141
|
-
self.host_registry = PinnedHostWeightRegistry()
|
|
142
|
-
self._init_mock_or_real_weights()
|
|
143
111
|
else:
|
|
144
112
|
# Fallback module template
|
|
145
113
|
self.embed_tokens = nn.Embedding(self.vocab_size, self.hidden_size).to(device)
|
|
@@ -202,33 +170,60 @@ class StreamLLMModel(nn.Module):
|
|
|
202
170
|
|
|
203
171
|
def _forward_layer(self, layer_module: nn.Module, hidden_states: torch.Tensor, layer_idx: int) -> torch.Tensor:
|
|
204
172
|
"""Executes a single transformer layer, handling HuggingFace return shapes and RoPE embeddings."""
|
|
205
|
-
if self.is_hf_transformer:
|
|
206
|
-
seq_len = hidden_states.shape[1]
|
|
207
|
-
pos_ids = torch.arange(seq_len, dtype=torch.long, device=hidden_states.device).unsqueeze(0)
|
|
208
|
-
pos_emb = None
|
|
209
|
-
if self.rotary_emb is not None:
|
|
210
|
-
try:
|
|
211
|
-
pos_emb = self.rotary_emb(hidden_states, pos_ids)
|
|
212
|
-
except Exception:
|
|
213
|
-
pass
|
|
214
|
-
try:
|
|
215
|
-
if pos_emb is not None:
|
|
216
|
-
out = layer_module(hidden_states, position_ids=pos_ids, position_embeddings=pos_emb)
|
|
217
|
-
else:
|
|
218
|
-
out = layer_module(hidden_states, position_ids=pos_ids)
|
|
219
|
-
if isinstance(out, (tuple, list)):
|
|
220
|
-
return out[0]
|
|
221
|
-
return out
|
|
222
|
-
except Exception:
|
|
223
|
-
try:
|
|
224
|
-
out = layer_module(hidden_states)
|
|
225
|
-
if isinstance(out, (tuple, list)):
|
|
226
|
-
return out[0]
|
|
227
|
-
return out
|
|
228
|
-
except Exception:
|
|
229
|
-
pass
|
|
230
173
|
return layer_module(hidden_states)
|
|
231
174
|
|
|
175
|
+
def _prepare_request(self, ids, limit):
|
|
176
|
+
length = ids.size(1) + limit
|
|
177
|
+
if limit < 0 or length > getattr(self.config, "max_position_embeddings", float("inf")):
|
|
178
|
+
raise ValueError("Requested generation exceeds the model context or has a negative limit")
|
|
179
|
+
heads = getattr(self.config, "num_attention_heads", 1)
|
|
180
|
+
kv_heads = getattr(self.config, "num_key_value_heads", heads)
|
|
181
|
+
width = getattr(self.config, "head_dim", None) or self.hidden_size // heads
|
|
182
|
+
cache_bytes = 2 * self.num_layers * ids.size(0) * length * kv_heads * width * self.embed_tokens.weight.element_size()
|
|
183
|
+
self.engine.prepare_residency(cache_bytes)
|
|
184
|
+
|
|
185
|
+
def _generation_state(self, use_cache):
|
|
186
|
+
if not self.is_hf_transformer:
|
|
187
|
+
return None, None
|
|
188
|
+
import inspect
|
|
189
|
+
from transformers.cache_utils import DynamicCache
|
|
190
|
+
|
|
191
|
+
params = inspect.signature(self.layer_template.forward).parameters
|
|
192
|
+
key = "past_key_values" if "past_key_values" in params else "past_key_value"
|
|
193
|
+
if key not in params or not hasattr(self.layer_template, "self_attn"):
|
|
194
|
+
raise ValueError("Unsupported decoder cache API")
|
|
195
|
+
return DynamicCache() if use_cache else None, key
|
|
196
|
+
|
|
197
|
+
def _generation_step(self, tokens, offset, cache, cache_key):
|
|
198
|
+
hidden = self.embed_tokens(tokens)
|
|
199
|
+
if cache_key is None:
|
|
200
|
+
return self.engine.forward_streamed(hidden, self._forward_layer)
|
|
201
|
+
|
|
202
|
+
positions = torch.arange(offset, offset + tokens.shape[1], device=self.device)
|
|
203
|
+
ids = positions.unsqueeze(0)
|
|
204
|
+
kwargs = {"position_ids": ids, "use_cache": cache is not None, cache_key: cache}
|
|
205
|
+
if self.rotary_emb is not None:
|
|
206
|
+
kwargs["position_embeddings"] = self.rotary_emb(hidden, ids)
|
|
207
|
+
if tokens.shape[1] > 1:
|
|
208
|
+
mask = hidden.new_full((tokens.shape[1], tokens.shape[1]), float("-inf"))
|
|
209
|
+
kwargs["attention_mask"] = mask.triu_(1)[None, None]
|
|
210
|
+
|
|
211
|
+
def forward(layer, x, index):
|
|
212
|
+
layer.self_attn.layer_idx = index
|
|
213
|
+
layer_kwargs = kwargs
|
|
214
|
+
window = getattr(layer.self_attn, "sliding_window", None)
|
|
215
|
+
if window is None and self.config.model_type == "mistral":
|
|
216
|
+
window = getattr(self.config, "sliding_window", None)
|
|
217
|
+
if window and offset + tokens.shape[1] > window:
|
|
218
|
+
keys = torch.arange(offset + tokens.shape[1], device=self.device)
|
|
219
|
+
disallowed = (keys > ids.T) | (keys <= ids.T - window)
|
|
220
|
+
mask = hidden.new_zeros(disallowed.shape).masked_fill_(disallowed, float("-inf"))
|
|
221
|
+
layer_kwargs = dict(kwargs, attention_mask=mask[None, None])
|
|
222
|
+
result = layer(x, **layer_kwargs)
|
|
223
|
+
return result[0] if isinstance(result, (tuple, list)) else result
|
|
224
|
+
|
|
225
|
+
return self.engine.forward_streamed(hidden, forward)
|
|
226
|
+
|
|
232
227
|
def generate(
|
|
233
228
|
self,
|
|
234
229
|
input_ids: torch.Tensor,
|
|
@@ -240,21 +235,20 @@ class StreamLLMModel(nn.Module):
|
|
|
240
235
|
"""Autoregressive generation loop with layer streaming."""
|
|
241
236
|
input_ids = input_ids.to(self.device)
|
|
242
237
|
sequences = input_ids.clone()
|
|
238
|
+
self._prepare_request(input_ids, max_new_tokens)
|
|
239
|
+
cache, cache_key = self._generation_state(use_cache)
|
|
240
|
+
offset = 0
|
|
243
241
|
|
|
244
242
|
with torch.no_grad():
|
|
245
243
|
for _ in range(max_new_tokens):
|
|
246
|
-
|
|
247
|
-
hidden_states = self.
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
hidden_states = self.engine.forward_streamed(
|
|
251
|
-
hidden_states,
|
|
252
|
-
layer_forward_fn=self._forward_layer,
|
|
253
|
-
)
|
|
244
|
+
tokens = sequences[:, offset:]
|
|
245
|
+
hidden_states = self._generation_step(tokens, offset, cache, cache_key)
|
|
246
|
+
if cache is not None:
|
|
247
|
+
offset = sequences.shape[1]
|
|
254
248
|
|
|
255
249
|
# 3. Final normalization and language model head projection
|
|
256
|
-
|
|
257
|
-
next_token_logits = self.lm_head(
|
|
250
|
+
last_hidden = self.norm(hidden_states[:, -1, :])
|
|
251
|
+
next_token_logits = self.lm_head(last_hidden)
|
|
258
252
|
|
|
259
253
|
# 4. Token selection
|
|
260
254
|
if temperature > 0.0:
|
|
@@ -284,22 +278,20 @@ class StreamLLMModel(nn.Module):
|
|
|
284
278
|
):
|
|
285
279
|
"""Yields generated token text chunks as they are produced in real time."""
|
|
286
280
|
input_ids = input_ids.to(self.device)
|
|
287
|
-
|
|
281
|
+
tokens = input_ids
|
|
282
|
+
self._prepare_request(input_ids, max_new_tokens)
|
|
283
|
+
cache, cache_key = self._generation_state(use_cache)
|
|
284
|
+
offset = 0
|
|
288
285
|
|
|
289
286
|
with torch.no_grad():
|
|
290
287
|
for step in range(max_new_tokens):
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
# 2. Stream all transformer layers through GPU double-buffer scratchpad
|
|
295
|
-
hidden_states = self.engine.forward_streamed(
|
|
296
|
-
hidden_states,
|
|
297
|
-
layer_forward_fn=self._forward_layer,
|
|
298
|
-
)
|
|
288
|
+
hidden_states = self._generation_step(tokens, offset, cache, cache_key)
|
|
289
|
+
if cache is not None:
|
|
290
|
+
offset += tokens.shape[1]
|
|
299
291
|
|
|
300
292
|
# 3. Final normalization and language model head projection
|
|
301
|
-
|
|
302
|
-
next_token_logits = self.lm_head(
|
|
293
|
+
last_hidden = self.norm(hidden_states[:, -1, :])
|
|
294
|
+
next_token_logits = self.lm_head(last_hidden)
|
|
303
295
|
|
|
304
296
|
# 4. Token selection
|
|
305
297
|
if temperature > 0.0:
|
|
@@ -308,17 +300,19 @@ class StreamLLMModel(nn.Module):
|
|
|
308
300
|
else:
|
|
309
301
|
next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
|
|
310
302
|
|
|
311
|
-
|
|
303
|
+
tokens = next_token if cache is not None else torch.cat([tokens, next_token], dim=-1)
|
|
312
304
|
|
|
313
305
|
# Decode real token chunk
|
|
314
|
-
|
|
306
|
+
token_ids = next_token.flatten().tolist()
|
|
307
|
+
token_val = token_ids[:1]
|
|
315
308
|
chunk = self.tokenizer.decode(token_val, skip_special_tokens=True)
|
|
316
309
|
yield chunk
|
|
317
310
|
|
|
318
311
|
# Check EOS
|
|
319
312
|
if self.tokenizer and hasattr(self.tokenizer, "eos_token_id") and self.tokenizer.eos_token_id is not None:
|
|
320
|
-
if (
|
|
321
|
-
|
|
313
|
+
if all(token == self.tokenizer.eos_token_id for token in token_ids):
|
|
314
|
+
return "eos"
|
|
315
|
+
return "length"
|
|
322
316
|
|
|
323
317
|
|
|
324
318
|
class MockTokenizer:
|
|
@@ -376,61 +370,20 @@ class AutoModel:
|
|
|
376
370
|
is_inst, size_str, snapshot_path = is_model_installed(resolved_name)
|
|
377
371
|
load_target = snapshot_path if snapshot_path else resolved_name
|
|
378
372
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
token=hf_token,
|
|
394
|
-
trust_remote_code=True,
|
|
395
|
-
)
|
|
396
|
-
except Exception as e:
|
|
397
|
-
if not is_inst:
|
|
398
|
-
raise RuntimeError(
|
|
399
|
-
f"Model '{pretrained_model_name_or_path}' is not installed locally and could not be reached online: {e}\n"
|
|
400
|
-
f"Run 'streamllm install {pretrained_model_name_or_path}' to download it."
|
|
401
|
-
)
|
|
402
|
-
pass
|
|
403
|
-
|
|
404
|
-
# Try loading real model weights into host memory for layer streaming
|
|
405
|
-
if AutoModelForCausalLM is not None and config is not None:
|
|
406
|
-
try:
|
|
407
|
-
hf_dtype = torch.float16 if (device.type == "cuda") else torch.float32
|
|
408
|
-
hf_model = AutoModelForCausalLM.from_pretrained(
|
|
409
|
-
load_target,
|
|
410
|
-
config=config,
|
|
411
|
-
torch_dtype=hf_dtype,
|
|
412
|
-
low_cpu_mem_usage=True,
|
|
413
|
-
token=hf_token,
|
|
414
|
-
trust_remote_code=True,
|
|
415
|
-
)
|
|
416
|
-
except Exception as e:
|
|
417
|
-
# If weights are missing locally
|
|
418
|
-
if not is_inst:
|
|
419
|
-
raise RuntimeError(
|
|
420
|
-
f"Model weights for '{pretrained_model_name_or_path}' are not downloaded.\n"
|
|
421
|
-
f"Please run 'streamllm install {pretrained_model_name_or_path}' to install it."
|
|
422
|
-
)
|
|
423
|
-
pass
|
|
424
|
-
|
|
425
|
-
if config is None:
|
|
426
|
-
class FallbackConfig:
|
|
427
|
-
hidden_size = 1024
|
|
428
|
-
num_hidden_layers = 8
|
|
429
|
-
vocab_size = 32000
|
|
430
|
-
config = FallbackConfig()
|
|
431
|
-
|
|
432
|
-
if tokenizer is None:
|
|
433
|
-
tokenizer = MockTokenizer()
|
|
373
|
+
if AutoModelForCausalLM is None:
|
|
374
|
+
raise ImportError("Install Transformers to load a checkpoint")
|
|
375
|
+
config = AutoConfig.from_pretrained(load_target, token=hf_token)
|
|
376
|
+
tokenizer = AutoTokenizer.from_pretrained(load_target, token=hf_token)
|
|
377
|
+
hf_model, loading = AutoModelForCausalLM.from_pretrained(
|
|
378
|
+
load_target, config=config, token=hf_token,
|
|
379
|
+
torch_dtype=torch.float16 if device.type == "cuda" else torch.float32,
|
|
380
|
+
low_cpu_mem_usage=True, output_loading_info=True,
|
|
381
|
+
)
|
|
382
|
+
if loading.get("missing_keys") or loading.get("mismatched_keys"):
|
|
383
|
+
raise ValueError(f"Incomplete checkpoint: {loading}")
|
|
384
|
+
if getattr(hf_model, "is_quantized", False):
|
|
385
|
+
raise ValueError("Streaming packed quantized weights is unsupported")
|
|
386
|
+
hf_model.eval()
|
|
434
387
|
|
|
435
388
|
model = StreamLLMModel(
|
|
436
389
|
config=config,
|
|
@@ -178,6 +178,44 @@ def cmd_hardware(args):
|
|
|
178
178
|
print("==================================================")
|
|
179
179
|
|
|
180
180
|
|
|
181
|
+
def cmd_decode_bench(args):
|
|
182
|
+
from statistics import median
|
|
183
|
+
device = resolve_device(args.device)
|
|
184
|
+
model = AutoModel.from_pretrained(args.model, device=device)
|
|
185
|
+
ids = encode_messages(model.tokenizer, [{"role": "user", "content": args.prompt}])
|
|
186
|
+
speeds = []
|
|
187
|
+
for run in range(args.runs + 1):
|
|
188
|
+
if device.type == "cuda":
|
|
189
|
+
torch.cuda.reset_peak_memory_stats(device)
|
|
190
|
+
start = time.perf_counter()
|
|
191
|
+
first = last = start
|
|
192
|
+
count = 0
|
|
193
|
+
for count, _ in enumerate(model.stream_generate(ids, max_new_tokens=args.max_tokens, temperature=0), 1):
|
|
194
|
+
last = time.perf_counter()
|
|
195
|
+
if count == 1:
|
|
196
|
+
first = last
|
|
197
|
+
if run:
|
|
198
|
+
elapsed = time.perf_counter() - start
|
|
199
|
+
speed = (count - 1) / (last - first) if count > 1 else 0
|
|
200
|
+
if count > 1:
|
|
201
|
+
speeds.append(speed)
|
|
202
|
+
print(f"Run {run}: {count} tokens, first {first-start:.3f}s, total {elapsed:.3f}s, decode {speed:.2f} tok/s")
|
|
203
|
+
if device.type == "cuda":
|
|
204
|
+
print(f"Peak allocated/reserved MiB: {torch.cuda.max_memory_allocated(device)/2**20:.1f}/"
|
|
205
|
+
f"{torch.cuda.max_memory_reserved(device)/2**20:.1f}; "
|
|
206
|
+
f"resident layers: {len(model.engine.resident_layers)}/{model.num_layers}")
|
|
207
|
+
streamed = model.num_layers - len(model.engine.resident_layers)
|
|
208
|
+
per_token = streamed * model.engine.scratchpad.active_slot.total_bytes()
|
|
209
|
+
pinned = sum(t.numel() * t.element_size() for layer in model.host_registry.layers.values()
|
|
210
|
+
for t in layer.values() if t.is_pinned())
|
|
211
|
+
print(f"Layer weight transfers per decode token: {per_token / 2**20:.1f} MiB; "
|
|
212
|
+
f"pinned host weights: {pinned / 2**20:.1f} MiB")
|
|
213
|
+
if speeds:
|
|
214
|
+
print(f"Median decode speed: {median(speeds):.2f} tok/s")
|
|
215
|
+
else:
|
|
216
|
+
print("Response ended before a decode interval could be measured.")
|
|
217
|
+
|
|
218
|
+
|
|
181
219
|
def cmd_bench(args):
|
|
182
220
|
print("==================================================")
|
|
183
221
|
print(" StreamLLM Micro-Benchmark: Streaming vs Overlap")
|
|
@@ -267,6 +305,50 @@ def cmd_bench(args):
|
|
|
267
305
|
print("--------------------------------------------------")
|
|
268
306
|
|
|
269
307
|
|
|
308
|
+
def encode_messages(tokenizer, messages):
|
|
309
|
+
if getattr(tokenizer, "chat_template", None):
|
|
310
|
+
encoded = tokenizer.apply_chat_template(
|
|
311
|
+
messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"
|
|
312
|
+
)
|
|
313
|
+
return encoded if isinstance(encoded, torch.Tensor) else encoded["input_ids"]
|
|
314
|
+
if len(messages) == 1:
|
|
315
|
+
prompt = messages[0]["content"]
|
|
316
|
+
else:
|
|
317
|
+
prompt = "\n".join(f"{msg['role'].title()}: {msg['content']}" for msg in messages) + "\nAssistant:"
|
|
318
|
+
return tokenizer(prompt, return_tensors="pt")["input_ids"]
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def measured_chunks(model, input_ids, args):
|
|
322
|
+
device = model.device
|
|
323
|
+
if device.type == "cuda":
|
|
324
|
+
torch.cuda.reset_peak_memory_stats(device)
|
|
325
|
+
start = time.perf_counter()
|
|
326
|
+
chunks = model.stream_generate(input_ids, max_new_tokens=args.max_tokens, temperature=args.temperature)
|
|
327
|
+
first = None
|
|
328
|
+
count = 0
|
|
329
|
+
last = None
|
|
330
|
+
while True:
|
|
331
|
+
try:
|
|
332
|
+
chunk = next(chunks)
|
|
333
|
+
except StopIteration as stop:
|
|
334
|
+
reason = stop.value
|
|
335
|
+
break
|
|
336
|
+
last = time.perf_counter() - start
|
|
337
|
+
count += 1
|
|
338
|
+
if first is None:
|
|
339
|
+
first = last
|
|
340
|
+
yield chunk
|
|
341
|
+
if reason == "length":
|
|
342
|
+
print(f"\nReached --max-tokens {args.max_tokens}. Increase the limit for a longer answer.", file=sys.stderr)
|
|
343
|
+
if first is not None and not getattr(args, "raw", False):
|
|
344
|
+
stats = f"Time to first token {first:.2f}s"
|
|
345
|
+
if count > 1 and last > first:
|
|
346
|
+
stats += f" | Output speed {(count - 1) / (last - first):.2f} tok/s"
|
|
347
|
+
if device.type == "cuda":
|
|
348
|
+
stats += f" | Peak allocated VRAM {torch.cuda.max_memory_allocated(device) / 2**20:.1f} MiB"
|
|
349
|
+
print(f"\n{stats}", file=sys.stderr)
|
|
350
|
+
|
|
351
|
+
|
|
270
352
|
def cmd_run(args):
|
|
271
353
|
"""Execute a single one-shot prompt with streaming output."""
|
|
272
354
|
model_name = resolve_chat_model(args.model)
|
|
@@ -296,17 +378,7 @@ def cmd_run(args):
|
|
|
296
378
|
|
|
297
379
|
model = AutoModel.from_pretrained(model_name, device=device)
|
|
298
380
|
|
|
299
|
-
|
|
300
|
-
try:
|
|
301
|
-
messages = [{"role": "user", "content": prompt_text}]
|
|
302
|
-
input_text = model.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
303
|
-
except Exception:
|
|
304
|
-
input_text = prompt_text
|
|
305
|
-
else:
|
|
306
|
-
input_text = prompt_text
|
|
307
|
-
|
|
308
|
-
tokens = model.tokenizer(input_text, return_tensors="pt")
|
|
309
|
-
input_ids = tokens["input_ids"]
|
|
381
|
+
input_ids = encode_messages(model.tokenizer, [{"role": "user", "content": prompt_text}])
|
|
310
382
|
|
|
311
383
|
if not args.raw and console:
|
|
312
384
|
console.print(f"\n[bold green]User:[/bold green] {prompt_text}")
|
|
@@ -318,7 +390,7 @@ def cmd_run(args):
|
|
|
318
390
|
start_time = time.perf_counter()
|
|
319
391
|
token_count = 0
|
|
320
392
|
|
|
321
|
-
for chunk in model
|
|
393
|
+
for chunk in measured_chunks(model, input_ids, args):
|
|
322
394
|
token_count += 1
|
|
323
395
|
if args.raw:
|
|
324
396
|
sys.stdout.write(chunk)
|
|
@@ -465,24 +537,18 @@ def cmd_chat(args):
|
|
|
465
537
|
print(f"Unknown command: {cmd}")
|
|
466
538
|
continue
|
|
467
539
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
prompt_with_context = f"System: {system_prompt}\nUser: {user_input}\nAssistant:"
|
|
481
|
-
else:
|
|
482
|
-
prompt_with_context = f"System: {system_prompt}\nUser: {user_input}\nAssistant:"
|
|
483
|
-
|
|
484
|
-
tokens = model.tokenizer(prompt_with_context, return_tensors="pt")
|
|
485
|
-
input_ids = tokens["input_ids"]
|
|
540
|
+
messages = [{"role": "system", "content": system_prompt}] if system_prompt else []
|
|
541
|
+
for user_text, answer in history:
|
|
542
|
+
messages.extend([{"role": "user", "content": user_text}, {"role": "assistant", "content": answer}])
|
|
543
|
+
messages.append({"role": "user", "content": user_input})
|
|
544
|
+
try:
|
|
545
|
+
input_ids = encode_messages(model.tokenizer, messages)
|
|
546
|
+
except Exception as error:
|
|
547
|
+
print(f"Could not format conversation: {error}", file=sys.stderr)
|
|
548
|
+
continue
|
|
549
|
+
if input_ids.size(1) + args.max_tokens > getattr(model.config, "max_position_embeddings", float("inf")):
|
|
550
|
+
print("Conversation exceeds the context budget. Use /clear or reduce --max-tokens.", file=sys.stderr)
|
|
551
|
+
continue
|
|
486
552
|
|
|
487
553
|
if console:
|
|
488
554
|
console.print("\n[bold green]Assistant:[/bold green] ", end="")
|
|
@@ -493,7 +559,7 @@ def cmd_chat(args):
|
|
|
493
559
|
token_count = 0
|
|
494
560
|
response_text = ""
|
|
495
561
|
|
|
496
|
-
for chunk in model
|
|
562
|
+
for chunk in measured_chunks(model, input_ids, args):
|
|
497
563
|
token_count += 1
|
|
498
564
|
response_text += chunk
|
|
499
565
|
if console:
|
|
@@ -558,7 +624,7 @@ def main():
|
|
|
558
624
|
p_chat = subparsers.add_parser("chat", help="Start an interactive chat session with live streaming")
|
|
559
625
|
p_chat.add_argument("model", nargs="?", default=None, help="Model preset (e.g. qwen-0.5b, smollm-135m, llama3-8b) or HuggingFace repo ID")
|
|
560
626
|
p_chat.add_argument("--system", type=str, default="You are a helpful and concise AI assistant.", help="System prompt")
|
|
561
|
-
p_chat.add_argument("--max-tokens", type=int, default=
|
|
627
|
+
p_chat.add_argument("--max-tokens", type=int, default=1024, help="Maximum new tokens per turn")
|
|
562
628
|
p_chat.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
|
|
563
629
|
p_chat.add_argument("--device", type=str, default="auto", help="Execution device (auto, cuda:0, cpu)")
|
|
564
630
|
p_chat.set_defaults(func=cmd_chat)
|
|
@@ -568,7 +634,7 @@ def main():
|
|
|
568
634
|
p_run.add_argument("model", nargs="?", default=None, help="Model preset (e.g. qwen-0.5b, smollm-135m, llama3-8b) or HuggingFace repo ID")
|
|
569
635
|
p_run.add_argument("prompt", nargs="?", default=None, help="Prompt text to send to the model")
|
|
570
636
|
p_run.add_argument("--prompt", "-p", dest="prompt_opt", default=None, help="Alternative prompt flag")
|
|
571
|
-
p_run.add_argument("--max-tokens", type=int, default=
|
|
637
|
+
p_run.add_argument("--max-tokens", type=int, default=1024, help="Maximum new tokens to generate")
|
|
572
638
|
p_run.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
|
|
573
639
|
p_run.add_argument("--device", type=str, default="auto", help="Execution device (auto, cuda:0, cpu)")
|
|
574
640
|
p_run.add_argument("--raw", action="store_true", help="Print only raw tokens (useful for piping to scripts)")
|
|
@@ -624,6 +690,14 @@ def main():
|
|
|
624
690
|
p_hw.add_argument("--bench-mb", type=int, default=128, help="PCIe benchmark buffer size in MB")
|
|
625
691
|
p_hw.set_defaults(func=cmd_hardware)
|
|
626
692
|
|
|
693
|
+
decode = subparsers.add_parser("decode-bench", help="Benchmark real-model greedy generation")
|
|
694
|
+
decode.add_argument("model")
|
|
695
|
+
decode.add_argument("--prompt", default="Explain how rainfall forms in detail.")
|
|
696
|
+
decode.add_argument("--runs", type=int, choices=range(1, 101), default=5)
|
|
697
|
+
decode.add_argument("--max-tokens", type=int, default=128)
|
|
698
|
+
decode.add_argument("--device", default="auto")
|
|
699
|
+
decode.set_defaults(func=cmd_decode_bench)
|
|
700
|
+
|
|
627
701
|
# bench
|
|
628
702
|
p_bench = subparsers.add_parser("bench", help="Run streaming vs sequential micro-benchmark")
|
|
629
703
|
p_bench.add_argument("--device", type=int, default=0, help="CUDA device index")
|
|
@@ -28,6 +28,7 @@ class StreamLLMEngine:
|
|
|
28
28
|
device: torch.device,
|
|
29
29
|
double_buffering: bool = True,
|
|
30
30
|
):
|
|
31
|
+
self.resident_layers = []
|
|
31
32
|
self.device = device
|
|
32
33
|
self.num_layers = num_layers
|
|
33
34
|
self.host_registry = host_registry
|
|
@@ -62,6 +63,24 @@ class StreamLLMEngine:
|
|
|
62
63
|
if name in slot_tensors:
|
|
63
64
|
param.data = slot_tensors[name]
|
|
64
65
|
|
|
66
|
+
def prepare_residency(self, cache_bytes):
|
|
67
|
+
if not self.double_buffering:
|
|
68
|
+
return
|
|
69
|
+
self._bind_slot_to_module(self.scratchpad.active_slot.tensors)
|
|
70
|
+
free, total = torch.cuda.mem_get_info(self.device)
|
|
71
|
+
layer_bytes = self.scratchpad.active_slot.total_bytes()
|
|
72
|
+
available = free + len(self.resident_layers) * layer_bytes
|
|
73
|
+
reserve = cache_bytes + max(total // 4, 512 * 1024**2)
|
|
74
|
+
target = min(self.num_layers, max(0, available - reserve) // layer_bytes)
|
|
75
|
+
del self.resident_layers[target:]
|
|
76
|
+
while len(self.resident_layers) < target:
|
|
77
|
+
host = self.host_registry.get_layer(len(self.resident_layers))
|
|
78
|
+
try:
|
|
79
|
+
weights = {name: host[name].to(self.device) for name in self.scratchpad.active_slot.tensors}
|
|
80
|
+
except torch.cuda.OutOfMemoryError:
|
|
81
|
+
break
|
|
82
|
+
self.resident_layers.append(weights)
|
|
83
|
+
|
|
65
84
|
def forward_streamed(
|
|
66
85
|
self,
|
|
67
86
|
hidden_states: torch.Tensor,
|
|
@@ -74,19 +93,19 @@ class StreamLLMEngine:
|
|
|
74
93
|
# -------------------------------------------------------------
|
|
75
94
|
# Double-Buffered Pipelined Forward Pass
|
|
76
95
|
# -------------------------------------------------------------
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
stream = self.transfer_engine.compute_stream or (torch.cuda.current_stream() if torch.cuda.is_available() else None)
|
|
80
|
-
self.scratchpad.active_slot.copy_from_host(
|
|
81
|
-
layer0_weights,
|
|
82
|
-
stream=stream,
|
|
83
|
-
)
|
|
84
|
-
if self.device.type == "cuda":
|
|
85
|
-
torch.cuda.synchronize(self.device)
|
|
86
|
-
|
|
96
|
+
stream = self.transfer_engine.compute_stream
|
|
97
|
+
stream.wait_stream(torch.cuda.current_stream(self.device))
|
|
87
98
|
x = hidden_states
|
|
99
|
+
with torch.cuda.stream(stream):
|
|
100
|
+
for index, weights in enumerate(self.resident_layers):
|
|
101
|
+
self._bind_slot_to_module(weights)
|
|
102
|
+
x = layer_forward_fn(self.layer_module, x, index) if layer_forward_fn else self.layer_module(x)
|
|
88
103
|
|
|
89
|
-
|
|
104
|
+
start = len(self.resident_layers)
|
|
105
|
+
if start < self.num_layers:
|
|
106
|
+
self.scratchpad.active_slot.copy_from_host(self.host_registry.get_layer(start), stream=stream)
|
|
107
|
+
|
|
108
|
+
for layer_idx in range(start, self.num_layers):
|
|
90
109
|
# Asynchronously prefetch Layer (idx + 1) into prefetch_slot
|
|
91
110
|
if layer_idx + 1 < self.num_layers:
|
|
92
111
|
next_weights = self.host_registry.get_layer(layer_idx + 1)
|
|
@@ -130,10 +149,8 @@ class StreamLLMEngine:
|
|
|
130
149
|
|
|
131
150
|
for layer_idx in range(self.num_layers):
|
|
132
151
|
weights = self.host_registry.get_layer(layer_idx)
|
|
133
|
-
stream =
|
|
152
|
+
stream = torch.cuda.current_stream(self.device) if self.device.type == "cuda" else None
|
|
134
153
|
slot.copy_from_host(weights, stream=stream)
|
|
135
|
-
if self.device.type == "cuda":
|
|
136
|
-
torch.cuda.synchronize(self.device)
|
|
137
154
|
|
|
138
155
|
self._bind_slot_to_module(slot.tensors)
|
|
139
156
|
if layer_forward_fn:
|
|
@@ -141,6 +158,4 @@ class StreamLLMEngine:
|
|
|
141
158
|
else:
|
|
142
159
|
x = self.layer_module(x)
|
|
143
160
|
|
|
144
|
-
if self.device.type == "cuda":
|
|
145
|
-
torch.cuda.synchronize(self.device)
|
|
146
161
|
return x
|
|
@@ -6,6 +6,7 @@ download/installation of open-source models, and memory profiling estimates.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
from dataclasses import dataclass
|
|
9
|
+
import json
|
|
9
10
|
import os
|
|
10
11
|
from pathlib import Path
|
|
11
12
|
import sys
|
|
@@ -182,6 +183,24 @@ class InstalledModelInfo:
|
|
|
182
183
|
snapshot_path: Optional[str]
|
|
183
184
|
|
|
184
185
|
|
|
186
|
+
def has_checkpoint(folder):
|
|
187
|
+
root = Path(folder)
|
|
188
|
+
if not (root / "config.json").is_file():
|
|
189
|
+
return False
|
|
190
|
+
for name in ("model.safetensors", "pytorch_model.bin"):
|
|
191
|
+
if (root / name).is_file():
|
|
192
|
+
return True
|
|
193
|
+
index = root / (name + ".index.json")
|
|
194
|
+
if index.is_file():
|
|
195
|
+
try:
|
|
196
|
+
shards = set(json.loads(index.read_text(encoding="utf-8"))["weight_map"].values())
|
|
197
|
+
if shards and all((root / shard).is_file() for shard in shards):
|
|
198
|
+
return True
|
|
199
|
+
except (ValueError, KeyError, AttributeError, OSError, TypeError):
|
|
200
|
+
continue
|
|
201
|
+
return False
|
|
202
|
+
|
|
203
|
+
|
|
185
204
|
def scan_installed_models() -> Dict[str, InstalledModelInfo]:
|
|
186
205
|
"""Scans the local HuggingFace cache to identify installed models and weights."""
|
|
187
206
|
installed: Dict[str, InstalledModelInfo] = {}
|
|
@@ -202,15 +221,10 @@ def scan_installed_models() -> Dict[str, InstalledModelInfo]:
|
|
|
202
221
|
has_weights = False
|
|
203
222
|
snapshot_dir = None
|
|
204
223
|
|
|
205
|
-
for rev in repo.revisions:
|
|
206
|
-
if
|
|
224
|
+
for rev in sorted(repo.revisions, key=lambda r: r.last_modified, reverse=True):
|
|
225
|
+
if has_checkpoint(rev.snapshot_path):
|
|
207
226
|
snapshot_dir = str(rev.snapshot_path)
|
|
208
|
-
|
|
209
|
-
name_lower = f.file_name.lower()
|
|
210
|
-
if name_lower.endswith((".safetensors", ".bin", ".pt", ".pth", ".gguf", ".awq")):
|
|
211
|
-
has_weights = True
|
|
212
|
-
break
|
|
213
|
-
if has_weights:
|
|
227
|
+
has_weights = True
|
|
214
228
|
break
|
|
215
229
|
|
|
216
230
|
installed[repo_id.lower()] = InstalledModelInfo(
|
|
@@ -235,7 +249,7 @@ def is_model_installed(name_or_preset: str) -> Tuple[bool, str, Optional[str]]:
|
|
|
235
249
|
|
|
236
250
|
# Check if user passed an existing local directory path
|
|
237
251
|
if os.path.isdir(resolved_repo):
|
|
238
|
-
return
|
|
252
|
+
return has_checkpoint(resolved_repo), "Local Folder", resolved_repo
|
|
239
253
|
|
|
240
254
|
installed_map = scan_installed_models()
|
|
241
255
|
info = installed_map.get(resolved_repo.lower())
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: streamllm
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Run bigger LLMs on smaller GPUs through intelligent, asynchronous layer streaming.
|
|
5
5
|
Author: StreamLLM Authors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -150,7 +150,7 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
150
150
|
- **Static GPU Scratchpad Pool (`GPUScratchpadPool`):** Pre-allocates two static VRAM buffer slots (Slot A and Slot B). Eliminates `cudaMalloc` and `cudaFree` churn during generation.
|
|
151
151
|
- **Dual CUDA Streams:** Dedicated `compute_stream` and `transfer_stream` with lock-free hardware event synchronization (`torch.cuda.Event`).
|
|
152
152
|
- **Pinned Host Memory:** Uses page-locked RAM (`torch.Tensor.pin_memory()`) for true non-blocking PCIe transfers.
|
|
153
|
-
- **KV-Cache Manager:**
|
|
153
|
+
- **KV-Cache Manager:** Generation reserves estimated KV storage for the requested context when choosing GPU-resident layers. Peak usage also depends on the prompt and available device memory.
|
|
154
154
|
|
|
155
155
|
---
|
|
156
156
|
|
|
@@ -168,3 +168,9 @@ During inference, StreamLLM keeps only the currently executing layer on the GPU
|
|
|
168
168
|
| **32 Layers** | 2048.2 MB | 278.85 ms | **265.03 ms** | **1.05x** | **128.0 MB** |
|
|
169
169
|
|
|
170
170
|
> **Key Takeaway:** Even as total model weights scale past 2.0 GB, StreamLLM's static scratchpad pool holds physical GPU memory strictly at **128.0 MB** while asynchronous prefetching delivers up to **1.28x faster inference**.
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
### Benchmark a real checkpoint
|
|
174
|
+
|
|
175
|
+
After installing the checkpoint, run `streamllm decode-bench deepseek-1.5b --device cuda:0 --max-tokens 128`.
|
|
176
|
+
The benchmark performs one warmup and five timed greedy runs. It reports time to first token, decode throughput after the first token, and CUDA memory peaks. Use the same prompt and generation limit for comparisons. Chat and one-shot generation default to 1,024 new tokens.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from transformers import Qwen2Config, Qwen2ForCausalLM
|
|
6
|
+
|
|
7
|
+
from streamllm.auto_model import MockTokenizer, StreamLLMModel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CachedGenerationTests(unittest.TestCase):
|
|
11
|
+
def setUp(self):
|
|
12
|
+
torch.manual_seed(19)
|
|
13
|
+
config = Qwen2Config(vocab_size=64, hidden_size=32, intermediate_size=64,
|
|
14
|
+
num_hidden_layers=3, num_attention_heads=4, num_key_value_heads=2)
|
|
15
|
+
self.reference = Qwen2ForCausalLM(config).eval()
|
|
16
|
+
self.model = StreamLLMModel(config, MockTokenizer(), torch.device("cpu"),
|
|
17
|
+
hf_model=copy.deepcopy(self.reference))
|
|
18
|
+
self.ids = torch.tensor([[5, 12, 9, 7]])
|
|
19
|
+
|
|
20
|
+
@torch.no_grad()
|
|
21
|
+
def test_cached_logits_match_reference(self):
|
|
22
|
+
cache, key = self.model._generation_state(True)
|
|
23
|
+
sequence = self.ids
|
|
24
|
+
offset = 0
|
|
25
|
+
for _ in range(5):
|
|
26
|
+
hidden = self.model._generation_step(sequence[:, offset:], offset, cache, key)
|
|
27
|
+
actual = self.model.lm_head(self.model.norm(hidden))
|
|
28
|
+
expected = self.reference(sequence, use_cache=False).logits[:, offset:]
|
|
29
|
+
torch.testing.assert_close(actual, expected, atol=1e-5, rtol=1e-4)
|
|
30
|
+
offset = sequence.size(1)
|
|
31
|
+
sequence = torch.cat([sequence, expected[:, -1].argmax(-1, keepdim=True)], dim=1)
|
|
32
|
+
|
|
33
|
+
def test_cached_and_uncached_greedy_generation(self):
|
|
34
|
+
cached = self.model.generate(self.ids, max_new_tokens=5).sequences
|
|
35
|
+
uncached = self.model.generate(self.ids, max_new_tokens=5, use_cache=False).sequences
|
|
36
|
+
self.assertTrue(torch.equal(cached, uncached))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|