innards 0.1.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.
- innards-0.1.0/LICENSE +201 -0
- innards-0.1.0/PKG-INFO +401 -0
- innards-0.1.0/README.md +367 -0
- innards-0.1.0/pyproject.toml +128 -0
- innards-0.1.0/pyproject.toml.orig +99 -0
- innards-0.1.0/src/innards/__init__.py +19 -0
- innards-0.1.0/src/innards/__main__.py +7 -0
- innards-0.1.0/src/innards/_text.py +76 -0
- innards-0.1.0/src/innards/backends/__init__.py +39 -0
- innards-0.1.0/src/innards/backends/base.py +156 -0
- innards-0.1.0/src/innards/backends/hf.py +505 -0
- innards-0.1.0/src/innards/backends/hf_cache.py +205 -0
- innards-0.1.0/src/innards/cli.py +200 -0
- innards-0.1.0/src/innards/collectors/__init__.py +6 -0
- innards-0.1.0/src/innards/collectors/memory.py +52 -0
- innards-0.1.0/src/innards/collectors/timing.py +32 -0
- innards-0.1.0/src/innards/kv/__init__.py +26 -0
- innards-0.1.0/src/innards/kv/calculator.py +223 -0
- innards-0.1.0/src/innards/kv/config.py +521 -0
- innards-0.1.0/src/innards/kv/dtypes.py +56 -0
- innards-0.1.0/src/innards/lineage/__init__.py +180 -0
- innards-0.1.0/src/innards/lineage/data/fp8_kv.json +16 -0
- innards-0.1.0/src/innards/lineage/data/gqa.json +19 -0
- innards-0.1.0/src/innards/lineage/data/hybrid.json +20 -0
- innards-0.1.0/src/innards/lineage/data/mha.json +19 -0
- innards-0.1.0/src/innards/lineage/data/mla.json +18 -0
- innards-0.1.0/src/innards/lineage/data/mqa.json +19 -0
- innards-0.1.0/src/innards/lineage/data/sliding_window.json +19 -0
- innards-0.1.0/src/innards/lineage/data/ssm.json +18 -0
- innards-0.1.0/src/innards/observe/__init__.py +21 -0
- innards-0.1.0/src/innards/observe/events.py +72 -0
- innards-0.1.0/src/innards/observe/observer.py +278 -0
- innards-0.1.0/src/innards/observe/queue.py +62 -0
- innards-0.1.0/src/innards/py.typed +0 -0
- innards-0.1.0/src/innards/schema.py +208 -0
- innards-0.1.0/src/innards/session.py +653 -0
- innards-0.1.0/src/innards/sinks/__init__.py +85 -0
- innards-0.1.0/src/innards/sinks/console.py +95 -0
- innards-0.1.0/src/innards/strategies/__init__.py +44 -0
innards-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
innards-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: innards
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: See inside open-weight LLMs per message: KV cache, context growth and memory, predicted vs measured, across MHA, GQA, MLA, sliding-window and hybrid models.
|
|
5
|
+
Keywords: llm,kv-cache,transformers,attention,gqa,mla,observability,profiling,inference
|
|
6
|
+
Author: Jai
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: System :: Monitoring
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Dist: httpx>=0.28.1
|
|
25
|
+
Requires-Dist: huggingface-hub>=1.5
|
|
26
|
+
Requires-Dist: psutil>=5.9 ; extra == 'hf'
|
|
27
|
+
Requires-Dist: torch>=2.4 ; extra == 'hf'
|
|
28
|
+
Requires-Dist: transformers>=5.0 ; extra == 'hf'
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Project-URL: Homepage, https://pypi.org/project/innards/
|
|
31
|
+
Project-URL: Documentation, https://pypi.org/project/innards/#description
|
|
32
|
+
Provides-Extra: hf
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# Innards
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
Innards runs open-weight LLMs and shows, for every message, what happens inside: tokens, context growth, KV cache per layer, memory and timing.
|
|
40
|
+
It predicts KV-cache size from the model config, measures the real cache, and explains what each attention design (MHA, GQA, MLA, sliding window, hybrid) changed from its predecessor.
|
|
41
|
+
Observation runs in background threads beside generation, so the model generates exactly as it would without Innards.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
<!-- test: install (checked by the fresh-environment wheel install in CI) -->
|
|
46
|
+
```bash
|
|
47
|
+
pip install innards # core: KV calculator, lineage, schema, console sink
|
|
48
|
+
pip install "innards[hf]" # + torch, transformers, psutil for in-process Hugging Face models
|
|
49
|
+
|
|
50
|
+
uv add innards # inside a uv project
|
|
51
|
+
uv add "innards[hf]"
|
|
52
|
+
uv pip install "innards[hf]" # into an existing environment
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The core install has two small dependencies (`httpx`, `huggingface-hub`) and works on any Python 3.10+. The `hf` extra adds PyTorch and Transformers.
|
|
56
|
+
|
|
57
|
+
## Quickstart
|
|
58
|
+
|
|
59
|
+
Chat with a model and get one record per message:
|
|
60
|
+
|
|
61
|
+
<!-- test: requires=hf,network -->
|
|
62
|
+
```python
|
|
63
|
+
from innards import Session
|
|
64
|
+
|
|
65
|
+
with Session(
|
|
66
|
+
"Qwen/Qwen3-0.6B", max_new_tokens=48, sinks=["console"], chat_template_kwargs={"enable_thinking": False}
|
|
67
|
+
) as s:
|
|
68
|
+
turn = s.chat("Explain paged attention in 3 lines")
|
|
69
|
+
print(turn.output.text)
|
|
70
|
+
print(turn.tokens.context_after, turn.kv.measured_bytes, turn.kv.predicted_bytes)
|
|
71
|
+
|
|
72
|
+
turn = s.chat("Now in one line")
|
|
73
|
+
print(turn.tokens.cached, "prompt tokens reused from the KV cache")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Send the same messages to models with different attention designs and compare:
|
|
77
|
+
|
|
78
|
+
<!-- test: requires=hf,network -->
|
|
79
|
+
```python
|
|
80
|
+
from innards import compare
|
|
81
|
+
|
|
82
|
+
results = compare(
|
|
83
|
+
models=["gpt2", "Qwen/Qwen3-0.6B"],
|
|
84
|
+
script=["What is a KV cache?", "Why does it grow with context?"],
|
|
85
|
+
max_new_tokens=16,
|
|
86
|
+
)
|
|
87
|
+
print(results.table())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Predict KV size without loading weights:
|
|
91
|
+
|
|
92
|
+
<!-- test: requires=network check-output -->
|
|
93
|
+
```python
|
|
94
|
+
from innards.kv import predict
|
|
95
|
+
|
|
96
|
+
p = predict("Qwen/Qwen3-0.6B", context_tokens=32768, kv_dtype="float16")
|
|
97
|
+
print(p.formula) # 2 × 28 layers × 8 KV heads × 128 head dim × 2 B = 114,688 B/token
|
|
98
|
+
print(p.kv_bytes) # 3758096384
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Imports
|
|
102
|
+
|
|
103
|
+
| Import | What it is |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| `from innards import Session` | Synchronous session: chat with one model, one `TurnRecord` per message |
|
|
106
|
+
| `from innards import AsyncSession` | Async session: streams tokens while metrics arrive from background workers |
|
|
107
|
+
| `from innards import compare` | Sends the same messages to several models and aligns the results |
|
|
108
|
+
| `from innards import CompareResult` | Result of `compare`: `turns[model]`, `rows()`, `table()`, `to_dict()` |
|
|
109
|
+
| `from innards import Turn` | Alias of `TurnRecord`, the return type of `Session.chat` |
|
|
110
|
+
| `from innards.kv import predict` | Architectural KV bytes, capacity and per-layer breakdown from a config, no weights |
|
|
111
|
+
| `from innards.kv import KVPrediction` | Result of `predict` |
|
|
112
|
+
| `from innards.kv import ModelSpec, LayerKV` | Normalized architecture facts and per-layer cache geometry |
|
|
113
|
+
| `from innards.kv import load_config, spec_from_config` | Read a config (Hub id, path, dict) and normalize it |
|
|
114
|
+
| `from innards.kv import dtype_bytes, normalize_dtype` | KV element types: `float32`, `float16`, `bfloat16`, `float8` |
|
|
115
|
+
| `from innards.lineage import explain` | What an architecture changed from its predecessor, and why |
|
|
116
|
+
| `from innards.lineage import LineageEntry, chain, families, get` | Lineage entries, predecessor chain, family list and lookup |
|
|
117
|
+
| `from innards.schema import TurnRecord` | The per-message record (schema v1.0) |
|
|
118
|
+
| `from innards.schema import ModelInfo, RuntimeInfo, TokenCounts, ContextComposition, KVInfo, MemoryInfo, TimingInfo, OutputInfo, ObserverInfo` | The record's sections |
|
|
119
|
+
| `from innards.sinks import Sink, ConsoleSink, CallbackSink, make_sink, register_sink` | Where records go; any `write(record)`/`close()` object or plain callable works |
|
|
120
|
+
| `from innards.observe import Observer, BoundedEventQueue` | The non-blocking observer and its drop-counting queue |
|
|
121
|
+
| `from innards.backends import Backend, get_backend, register_backend, ContextFullError` | Engine adapter interface and registry |
|
|
122
|
+
| `from innards.backends.hf import HFBackend` | In-process Hugging Face Transformers backend (needs `innards[hf]`) |
|
|
123
|
+
| `from innards.strategies import FullHistory` | Context strategy that keeps every turn and reuses the KV cache |
|
|
124
|
+
|
|
125
|
+
## Functions
|
|
126
|
+
|
|
127
|
+
### `Session`
|
|
128
|
+
|
|
129
|
+
```text
|
|
130
|
+
Session(model: str, backend: str = "hf", strategy: str = "full_history",
|
|
131
|
+
sinks: Iterable[str | Sink | Callable] | None = None, *, system: str | None = None,
|
|
132
|
+
observe: bool = True, max_new_tokens: int = 256, record_timeout: float = 30.0,
|
|
133
|
+
queue_size: int = 4096, run_id: str | None = None, session_id: str | None = None,
|
|
134
|
+
load: bool = True, **backend_kwargs) -> Session
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- `model`: Hugging Face Hub repo id or local path.
|
|
138
|
+
- `backend`: `"hf"` (in-process Transformers).
|
|
139
|
+
- `strategy`: `"full_history"`: every turn is kept, and the KV cache from earlier turns is reused.
|
|
140
|
+
- `sinks`: where finished records go, e.g. `["console"]`. Records are also returned by `chat`.
|
|
141
|
+
- `system`: optional system prompt.
|
|
142
|
+
- `observe`: `False` turns observation off entirely (no events, no worker threads).
|
|
143
|
+
- `max_new_tokens`: generation budget per turn (greedy decoding).
|
|
144
|
+
- `record_timeout`: how long `chat` waits for the background record after generation has finished.
|
|
145
|
+
- `**backend_kwargs`: for `hf`: `device` (`"cpu"`, `"cuda"`, `"mps"`), `dtype`, `chat_template_kwargs`, `generation_kwargs`, `revision`, `token`, `trust_remote_code`.
|
|
146
|
+
|
|
147
|
+
Returns a session bound to one model. Use it as a context manager, or call `close()`.
|
|
148
|
+
|
|
149
|
+
<!-- test: requires=hf,network check-output -->
|
|
150
|
+
```python
|
|
151
|
+
from innards import Session
|
|
152
|
+
|
|
153
|
+
s = Session("gpt2", device="cpu", max_new_tokens=16)
|
|
154
|
+
print(s.backend.spec.architecture) # mha
|
|
155
|
+
s.close()
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### `Session.chat`
|
|
159
|
+
|
|
160
|
+
```text
|
|
161
|
+
Session.chat(message: str, *, timeout: float | None = None) -> TurnRecord
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
- `message`: the user message.
|
|
165
|
+
- `timeout`: seconds to wait for the background record (default: `record_timeout`).
|
|
166
|
+
|
|
167
|
+
Returns the `TurnRecord` (also available as `Turn`) with output text, tokens, KV, memory and timing.
|
|
168
|
+
|
|
169
|
+
<!-- test: requires=hf,network -->
|
|
170
|
+
```python
|
|
171
|
+
from innards import Session
|
|
172
|
+
|
|
173
|
+
with Session("gpt2", max_new_tokens=16) as s:
|
|
174
|
+
turn = s.chat("The key-value cache")
|
|
175
|
+
print(turn.kv.cache_tokens, turn.kv.measured_bytes == turn.kv.predicted_bytes) # e.g. 23 True
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### `Session.stream` and `Session.turn_metrics`
|
|
179
|
+
|
|
180
|
+
```text
|
|
181
|
+
Session.stream(message: str) -> Iterator[str]
|
|
182
|
+
Session.turn_metrics(timeout: float | None = None) -> TurnRecord
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
- `stream` yields text as it is generated; closing the iterator early cancels generation.
|
|
186
|
+
- `turn_metrics` returns the record for the most recent turn, waiting for the background worker if needed.
|
|
187
|
+
|
|
188
|
+
<!-- test: requires=hf,network -->
|
|
189
|
+
```python
|
|
190
|
+
from innards import Session
|
|
191
|
+
|
|
192
|
+
with Session("gpt2", max_new_tokens=16) as s:
|
|
193
|
+
for piece in s.stream("Attention is"):
|
|
194
|
+
print(piece, end="", flush=True)
|
|
195
|
+
print()
|
|
196
|
+
print(s.turn_metrics().timing)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### `AsyncSession`
|
|
200
|
+
|
|
201
|
+
```text
|
|
202
|
+
AsyncSession(model: str, backend: str = "hf", **session_kwargs) -> AsyncSession
|
|
203
|
+
async AsyncSession.stream(message: str) -> AsyncIterator[str]
|
|
204
|
+
await AsyncSession.turn_metrics(timeout: float | None = None) -> TurnRecord
|
|
205
|
+
await AsyncSession.chat(message: str) -> TurnRecord
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Takes the same arguments as `Session`. The model loads and generates in worker threads, so the event loop is never blocked.
|
|
209
|
+
|
|
210
|
+
<!-- test: requires=hf,network -->
|
|
211
|
+
```python
|
|
212
|
+
import asyncio
|
|
213
|
+
from innards import AsyncSession
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def main():
|
|
217
|
+
async with AsyncSession("gpt2", max_new_tokens=16) as s:
|
|
218
|
+
async for token in s.stream("Explain paged attention"):
|
|
219
|
+
print(token, end="", flush=True) # generation never waits on Innards
|
|
220
|
+
turn = await s.turn_metrics() # arrives from background workers
|
|
221
|
+
print()
|
|
222
|
+
print(turn.kv.measured_bytes)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
asyncio.run(main())
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### `compare`
|
|
229
|
+
|
|
230
|
+
```text
|
|
231
|
+
compare(models: Sequence[str], script: str | PathLike | Sequence[str], backend: str = "hf",
|
|
232
|
+
**session_kwargs) -> CompareResult
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
- `models`: Hub repo ids or local paths, run one at a time.
|
|
236
|
+
- `script`: a list of user messages, one message, or a JSON file with a list of messages (strings or `{"content": ...}` objects, optionally under `"messages"`).
|
|
237
|
+
- `**session_kwargs`: passed to every `Session`.
|
|
238
|
+
|
|
239
|
+
Returns a `CompareResult`: `turns[model]` is the list of records; `rows()`, `table()` and `to_dict()` align them by turn.
|
|
240
|
+
|
|
241
|
+
<!-- test: requires=hf,network -->
|
|
242
|
+
```python
|
|
243
|
+
import json, pathlib, tempfile
|
|
244
|
+
from innards import compare
|
|
245
|
+
|
|
246
|
+
path = pathlib.Path(tempfile.mkdtemp()) / "script.json"
|
|
247
|
+
path.write_text(json.dumps({"messages": ["Hello", "What did I just say?"]}))
|
|
248
|
+
result = compare(["gpt2"], path, max_new_tokens=8)
|
|
249
|
+
print(result.rows()[0]["kv_measured_bytes"])
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### `predict`
|
|
253
|
+
|
|
254
|
+
```text
|
|
255
|
+
predict(model_or_config: str | PathLike | dict | PretrainedConfig | ModelSpec, context_tokens: int,
|
|
256
|
+
kv_dtype: str = "float16", *, memory_bytes: int | None = None, batch_size: int = 1,
|
|
257
|
+
revision: str | None = None, token: str | None = None) -> KVPrediction
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
- `model_or_config`: Hub repo id (only `config.json` is downloaded), a config path or directory, a dict, a `PretrainedConfig` or a `ModelSpec`.
|
|
261
|
+
- `context_tokens`: tokens resident in the cache.
|
|
262
|
+
- `kv_dtype`: `float32`, `float16`, `bfloat16` or `float8` (aliases `fp32`, `fp16`, `bf16`, `fp8`).
|
|
263
|
+
- `memory_bytes`: optional KV budget; sets `capacity_tokens`.
|
|
264
|
+
|
|
265
|
+
Returns a `KVPrediction` with `bytes_per_token`, `kv_bytes`, `recurrent_state_bytes`, `total_bytes`, `per_layer_bytes`, `by_layer_type`, `capacity_tokens`, `formula` and `notes`. "Architectural" KV is what the attention design needs; an engine may hold more, and Innards reports the gap instead of hiding it. Sliding-window layers hold `window - 1` tokens: the current token attends to itself plus `window - 1` cached ones.
|
|
266
|
+
|
|
267
|
+
<!-- test: requires=network check-output -->
|
|
268
|
+
```python
|
|
269
|
+
from innards.kv import predict
|
|
270
|
+
|
|
271
|
+
p = predict("deepseek-ai/DeepSeek-V2-Lite", context_tokens=32768, memory_bytes=8 * 2**30)
|
|
272
|
+
print(p.architecture, p.bytes_per_token, p.capacity_tokens) # mla 31104 163840
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
A config dict works offline:
|
|
276
|
+
|
|
277
|
+
<!-- test: check-output -->
|
|
278
|
+
```python
|
|
279
|
+
from innards.kv import predict
|
|
280
|
+
|
|
281
|
+
gemma_like = {
|
|
282
|
+
"model_type": "gemma3_text",
|
|
283
|
+
"num_hidden_layers": 26,
|
|
284
|
+
"num_attention_heads": 4,
|
|
285
|
+
"num_key_value_heads": 1,
|
|
286
|
+
"head_dim": 256,
|
|
287
|
+
"sliding_window": 512,
|
|
288
|
+
"sliding_window_pattern": 6,
|
|
289
|
+
"max_position_embeddings": 32768,
|
|
290
|
+
}
|
|
291
|
+
p = predict(gemma_like, context_tokens=8192, kv_dtype="bf16")
|
|
292
|
+
print(p.by_layer_type) # {'global': 33554432, 'sliding': 11511808, 'recurrent': 0}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### `explain`
|
|
296
|
+
|
|
297
|
+
```text
|
|
298
|
+
explain(model_or_architecture: str | PathLike | dict | ModelSpec) -> LineageEntry
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
- `model_or_architecture`: a family name or alias (`"mha"`, `"mqa"`, `"gqa"`, `"mla"`, `"sliding_window"`, `"hybrid"`, `"ssm"`, `"fp8"`), a Hub repo id, a config path or dict, or a `ModelSpec`.
|
|
302
|
+
|
|
303
|
+
Returns a `LineageEntry` with `family`, `predecessor`, `change`, `problem_solved`, `trade_off`, `kv_formula` and `reference`. For a model, `detail` describes that model's own numbers.
|
|
304
|
+
|
|
305
|
+
<!-- test: check-output -->
|
|
306
|
+
```python
|
|
307
|
+
from innards.lineage import explain
|
|
308
|
+
|
|
309
|
+
entry = explain("gqa")
|
|
310
|
+
print(entry.predecessor, "->", entry.family) # mha -> gqa
|
|
311
|
+
print(entry.problem_solved)
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
<!-- test: requires=network -->
|
|
315
|
+
```python
|
|
316
|
+
from innards.lineage import explain
|
|
317
|
+
|
|
318
|
+
print(explain("deepseek-ai/DeepSeek-V2-Lite")) # MLA: what it changed from GQA and why
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
### `TurnRecord`
|
|
322
|
+
|
|
323
|
+
```text
|
|
324
|
+
TurnRecord.to_dict() -> dict
|
|
325
|
+
TurnRecord.to_json(**json_kwargs) -> str
|
|
326
|
+
TurnRecord.from_dict(data: dict) -> TurnRecord
|
|
327
|
+
TurnRecord.from_json(text: str) -> TurnRecord
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
One JSON record per message, schema v1.0: `model`, `runtime`, `tokens`, `context`, `kv`, `memory`, `timing`, `output` and `observer`. Missing measurements are `null`, never zero. Readers accept any 1.x record and reject other major versions.
|
|
331
|
+
|
|
332
|
+
<!-- test: check-output -->
|
|
333
|
+
```python
|
|
334
|
+
from innards.schema import TurnRecord
|
|
335
|
+
|
|
336
|
+
record = TurnRecord.from_dict(
|
|
337
|
+
{
|
|
338
|
+
"schema_version": "1.0",
|
|
339
|
+
"session_id": "s-1",
|
|
340
|
+
"turn": 1,
|
|
341
|
+
"timestamp": "2026-10-01T10:42:07Z",
|
|
342
|
+
"model": {"id": "Qwen/Qwen3-0.6B", "architecture": "gqa"},
|
|
343
|
+
"runtime": {"backend": "hf"},
|
|
344
|
+
"kv": {"predicted_bytes": 378929152, "measured_bytes": 378929152, "measured_source": "hf_cache"},
|
|
345
|
+
}
|
|
346
|
+
)
|
|
347
|
+
print(record.kv.measured_bytes, record.memory.peak_bytes) # 378929152 None
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
## CLI
|
|
351
|
+
|
|
352
|
+
<!-- test: cli -->
|
|
353
|
+
```bash
|
|
354
|
+
innards chat --model gpt2 --backend hf # chat; per-turn metrics on stderr
|
|
355
|
+
innards chat --model Qwen/Qwen3-0.6B --no-think --json # TurnRecord JSON after each turn
|
|
356
|
+
innards predict --model Qwen/Qwen3-0.6B --context 32768 --kv-dtype fp8
|
|
357
|
+
innards predict --model deepseek-ai/DeepSeek-V2-Lite --context 32768 --memory 16GiB --json
|
|
358
|
+
innards explain sliding_window
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
`innards chat` streams the reply to stdout and prints a three-line summary per turn to stderr: prompt, cached and generated tokens; KV measured vs predicted by layer type; TTFT, prefill, decode speed, peak memory and dropped events. Type `/reset` to start over, `/exit` to quit. Options: `--system`, `--max-new-tokens`, `--device`, `--dtype`, `--no-think`, `--json`, `--no-metrics`.
|
|
362
|
+
|
|
363
|
+
## Supported
|
|
364
|
+
|
|
365
|
+
**Architectures** (KV calculator and HF measurements):
|
|
366
|
+
|
|
367
|
+
| Family | What is cached | Examples |
|
|
368
|
+
| --- | --- | --- |
|
|
369
|
+
| MHA | K and V for every head | GPT-2, Phi-3-mini (its config also sets a 2,047-token window on every layer) |
|
|
370
|
+
| MQA | One shared K/V head | GPT-BigCode, Falcon-7B |
|
|
371
|
+
| GQA | K/V per head group | Qwen3, Llama 3.2 |
|
|
372
|
+
| MLA | Compressed latent + RoPE key | DeepSeek-V2, DeepSeek-V3 |
|
|
373
|
+
| Sliding window (+ global) | Local layers keep `window - 1` tokens | Gemma 2/3, GPT-OSS, OLMo 3, Cohere 2, EXAONE 4, Mistral 7B v0.1; Llama 4 chunked layers |
|
|
374
|
+
| Hybrid | Attention KV in a few layers + fixed recurrent state | Granite 4.0-H, LFM2, Qwen3-Next, Jamba, Bamba, Falcon-H1, Nemotron-H |
|
|
375
|
+
| SSM | Fixed recurrent state only | Mamba, Mamba-2 |
|
|
376
|
+
|
|
377
|
+
Legacy config keys (`n_layer`, `n_head`, `n_embd`, ChatGLM, Falcon, MPT) and nested `text_config` (multimodal checkpoints) are read too. KV dtypes: fp32, fp16, bf16, fp8.
|
|
378
|
+
|
|
379
|
+
**Backends:** `hf`, in-process Hugging Face Transformers 5.x on CPU, CUDA or Apple MPS. Remote engines (vLLM, Ollama, llama.cpp) and managed APIs use the same `TurnRecord` and plug in through `innards.backends.register_backend`. They are planned, not shipped yet.
|
|
380
|
+
|
|
381
|
+
**Sinks:** `console` (text or JSON lines). Any object with `write(record)` and `close()`, or a plain callable, also works as a sink.
|
|
382
|
+
|
|
383
|
+
**Environments:** anywhere Python runs: local terminal, Jupyter and VS Code, Docker, cloud VMs and containers (AWS, GCP, Azure), Kaggle and Colab.
|
|
384
|
+
|
|
385
|
+
**Python:** 3.10, 3.11, 3.12, 3.13 and 3.14. Python 3.15 is tested against its release candidates, with support from the final release (1 October 2026). The core install runs on 3.15 today. The `hf` extra needs PyTorch wheels for your Python version, and PyTorch has none for 3.15 yet.
|
|
386
|
+
|
|
387
|
+
## Non-blocking guarantee
|
|
388
|
+
|
|
389
|
+
Innards never sits in the generation path:
|
|
390
|
+
|
|
391
|
+
- **Hot path**: the only Innards code inside the token loop takes a timestamp and offers a small event to a bounded queue. It makes no network calls, disk writes, tensor copies or device synchronization.
|
|
392
|
+
- **Bounded queues that never block**: when the per-token queue is full, the event is dropped and counted, never waited on. Every record carries `observer.dropped_events`, so gaps are visible. The two per-turn events (start and end, sent outside the token loop) are never dropped, so every message gets a record.
|
|
393
|
+
- **Background workers**: KV math, cache measurement (tensor shapes and dtypes only, `numel × element_size`), memory sampling and sink writes all run in background threads.
|
|
394
|
+
- **Fail-open**: if a collector or sink fails, the error is logged and counted, and generation continues.
|
|
395
|
+
- **Same output**: greedy output with Innards is identical to plain `model.generate`, which the test suite checks.
|
|
396
|
+
|
|
397
|
+
**Overhead budget:** throughput within 1% of running without Innards, and no added time to first token. `scripts/overhead_bench.py` measures it (same model and prompts, Innards on vs off, interleaved runs, medians).
|
|
398
|
+
|
|
399
|
+
## License
|
|
400
|
+
|
|
401
|
+
Apache-2.0
|