ftgate 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.
ftgate-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
ftgate-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: ftgate
3
+ Version: 0.1.0
4
+ Summary: Regression checks for small fine-tuned models on tool calling: do runtimes send the bytes the model was trained on?
5
+ Author: Vitalii Bogachev
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/talhayme/ftgate
8
+ Project-URL: Repository, https://github.com/talhayme/ftgate
9
+ Project-URL: Issues, https://github.com/talhayme/ftgate/issues
10
+ Keywords: fine-tuning,tool-calling,ollama,llama.cpp,gguf,evaluation,dataset,lint
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: transformers>=4.45
21
+ Requires-Dist: requests>=2.31
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # ftgate (working name)
27
+
28
+ Regression checks for a small model you fine-tuned on tool calling: do the
29
+ bytes the runtime sends match the bytes the model was trained on, and does
30
+ it still call your tools correctly after export and quantisation?
31
+
32
+ **Status: `ftgate template`, `ftgate data` and `ftgate tools` work.** The premise was
33
+ checked before any tool code was written — the same way
34
+ [pr-witness](https://github.com/talhayme/pr-witness) was built.
35
+
36
+ ## What has been measured so far
37
+
38
+ - **llama-server reproduces the HF training bytes exactly** for a
39
+ tool-calling prompt (Qwen2.5-0.5B-Instruct, 250/250 tokens, text and ids
40
+ identical) — even though the GGUF's embedded template hashes differently
41
+ from HF's. Compare renderings, never hashes. → [`notes/day1-findings.md`](notes/day1-findings.md)
42
+ - **Ollama 0.40.2 hands the model a Go struct dump instead of the tool
43
+ schema**: `{get_weather … {object <nil> <nil> [city] {…}}}`. Root cause
44
+ in `template/template.go` (`templateToolFunction` has no `String()`);
45
+ known upstream as ollama/ollama#14601 with open PRs #18318 and #18391.
46
+ - **Qwen's official Qwen2.5 GGUFs embed the pre-fix chat template** —
47
+ doubled braces `{{"name": …}}` in the tool-call instruction, fixed on HF
48
+ on 2024-09-19 but never regenerated in the GGUF repos. Ollama's library
49
+ blobs are those files. Ollama never renders it; llama.cpp, vLLM or LM
50
+ Studio serving the file do. **The 0.5B model copies the braces into
51
+ every tool call** (invalid JSON; a strict parser gets 0/35 where the HF
52
+ template gets 22/35); the 1.5B model ignores them. llama-server's parser
53
+ forgives it, vLLM's `json.loads` would not.
54
+ → [`notes/day4-doubled-braces-impact.md`](notes/day4-doubled-braces-impact.md)
55
+ → [`notes/day3-template-command.md`](notes/day3-template-command.md)
56
+ - **Ollama prepends the Modelfile SYSTEM** when a request has none — a
57
+ system prompt your training rows may never have had.
58
+ - **It costs accuracy.** Same GGUF blob in every arm, temperature 0, 40
59
+ cases: Qwen2.5-0.5B gets exact arguments 39/40 with its own template and
60
+ 31/40 with the prompt Ollama builds — every failure an invented
61
+ parameter `amount from_currency`, read off Go's `[amount from_currency
62
+ to_currency]` rendering of `required`. Qwen2.5-1.5B: 40/40 either way on
63
+ this easy set. → [`notes/day2-impact.md`](notes/day2-impact.md)
64
+
65
+ ## Use
66
+
67
+ ```
68
+ uv pip install -e .
69
+ ftgate template --model Qwen/Qwen2.5-0.5B-Instruct \
70
+ --llama http://localhost:8080 \
71
+ --ollama qwen2.5:0.5b-instruct \
72
+ --dataset train.jsonl --sample 20 --diff
73
+ ```
74
+
75
+ `--model` is the HF checkpoint whose tokenizer and chat template the
76
+ trainer used; `--dataset` is your own rows (`messages[, tools]` per line).
77
+ Each runtime's prompt and token ids are compared with what SFT fed the
78
+ model, and every difference is classified: `schema_not_json`,
79
+ `injected_system`, `special_prefix`, `structural`, `spacing`, `tokenizer`.
80
+ Ollama's column is rendered with Ollama's own `template` package (build
81
+ `bin/` once) and cross-checked against the live `prompt_eval_count`.
82
+
83
+ ### `ftgate data` — lint the dataset with the model's own tokenizer and template
84
+
85
+ ```
86
+ ftgate data train.jsonl --model Qwen/Qwen2.5-0.5B-Instruct --max-seq-len 2048 \
87
+ --eval eval.jsonl --fail-on error
88
+ ```
89
+
90
+ Rows in `messages`, ShareGPT, Alpaca or preference (`chosen`/`rejected`)
91
+ shape. Reports what the trainer will silently do to each row: an assistant
92
+ turn that renders to zero target tokens, a conversation cut by
93
+ `max_seq_len` before the answer (trains nothing) or inside it, a row that
94
+ never ends with EOS, a template that raises on the row. Structural checks:
95
+ empty or missing assistant target, role order, tool calls against the
96
+ declared schema (missing required / unknown arguments / undeclared tool /
97
+ `tool_call_id` with no call), `chosen == rejected`, length bias in
98
+ preference pairs, exact duplicates, near-duplicates of the eval set.
99
+ `--format json` for CI; `--fail-on error|warning` sets the exit code.
100
+
101
+ ### `ftgate tools` — does it still call *your* tools, on the backend it will run on?
102
+
103
+ ```
104
+ ftgate tools --tools tools.json --cases cases.jsonl \
105
+ --provider ollama:my-finetune:q4_k_m \
106
+ --provider "openai:m@http://localhost:8080/v1" \
107
+ --min-exact 0.8
108
+ ftgate tools --from-dataset train.jsonl --holdout 50 --provider ollama:my-finetune
109
+ ```
110
+
111
+ Evaluation runs on [promptfoo](https://www.promptfoo.dev/) (installed
112
+ once with `npm install --prefix .pfrunner promptfoo`, or set
113
+ `FTGATE_PROMPTFOO`). ftgate writes the config — your tools, your cases
114
+ (a file, or rows held out of your own training set), one provider per
115
+ arm, temperature 0, one request in flight for local servers — and a
116
+ deterministic judge that reports per case: the right tool, every expected
117
+ argument present and equal (extra optional arguments allowed and counted),
118
+ and two things a generic eval does not separate from "the model was
119
+ wrong": **parser lost** — the model emitted a `<tool_call>` the provider
120
+ did not surface — and **malformed** — the call's JSON does not parse.
121
+ Failure reasons show the produced arguments next to the expected ones.
122
+
123
+ ### In CI, in tests, before commit
124
+
125
+ ```yaml
126
+ # GitHub Actions
127
+ - uses: talhayme/ftgate@main
128
+ with: { dataset: data/train.jsonl, model: Qwen/Qwen2.5-0.5B-Instruct, max-seq-len: "2048" }
129
+ ```
130
+
131
+ ```yaml
132
+ # .pre-commit-config.yaml
133
+ - repo: https://github.com/talhayme/ftgate
134
+ rev: main
135
+ hooks: [{ id: ftgate-data, args: [--fail-on, error] }]
136
+ ```
137
+
138
+ ```python
139
+ # tests/test_data.py
140
+ from ftgate.testing import assert_dataset_clean
141
+
142
+ def test_training_data():
143
+ assert_dataset_clean("data/train.jsonl", model="Qwen/Qwen2.5-0.5B-Instruct", max_seq_len=2048)
144
+ ```
145
+
146
+ or, with the plugin that installs alongside the package,
147
+ `pytest --ftgate-dataset data/train.jsonl --ftgate-model Qwen/Qwen2.5-0.5B-Instruct`.
148
+
149
+ ## Reproduce the findings
150
+
151
+ ```
152
+ uv venv --python 3.12 ~/.venvs/ftgate && uv pip install --python ~/.venvs/ftgate/bin/python torch transformers gguf requests
153
+ # llama-server built from llama.cpp with --jinja support; Ollama ≥ 0.40 running on :11434
154
+ python scripts/hf_side.py # training-side bytes
155
+ python scripts/llama_side.py http://localhost:8089
156
+ python scripts/ollama_side.py # needs bin/ollama-render (see bin/README.md)
157
+ python scripts/day2_eval.py qwen2.5:0.5b-instruct # three-arm accuracy comparison
158
+ ```
159
+
160
+ ## Plan
161
+
162
+ `ftgate template` — the three-sided byte comparison as a command.
163
+ `ftgate data` — a linter for SFT/DPO/tool-call datasets using the target
164
+ model's tokenizer and template. Tool-call evaluation builds on promptfoo's
165
+ `tool-call-f1` / `trajectory:tool-args-match` rather than duplicating them.
166
+
167
+ Apache-2.0.
ftgate-0.1.0/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # ftgate (working name)
2
+
3
+ Regression checks for a small model you fine-tuned on tool calling: do the
4
+ bytes the runtime sends match the bytes the model was trained on, and does
5
+ it still call your tools correctly after export and quantisation?
6
+
7
+ **Status: `ftgate template`, `ftgate data` and `ftgate tools` work.** The premise was
8
+ checked before any tool code was written — the same way
9
+ [pr-witness](https://github.com/talhayme/pr-witness) was built.
10
+
11
+ ## What has been measured so far
12
+
13
+ - **llama-server reproduces the HF training bytes exactly** for a
14
+ tool-calling prompt (Qwen2.5-0.5B-Instruct, 250/250 tokens, text and ids
15
+ identical) — even though the GGUF's embedded template hashes differently
16
+ from HF's. Compare renderings, never hashes. → [`notes/day1-findings.md`](notes/day1-findings.md)
17
+ - **Ollama 0.40.2 hands the model a Go struct dump instead of the tool
18
+ schema**: `{get_weather … {object <nil> <nil> [city] {…}}}`. Root cause
19
+ in `template/template.go` (`templateToolFunction` has no `String()`);
20
+ known upstream as ollama/ollama#14601 with open PRs #18318 and #18391.
21
+ - **Qwen's official Qwen2.5 GGUFs embed the pre-fix chat template** —
22
+ doubled braces `{{"name": …}}` in the tool-call instruction, fixed on HF
23
+ on 2024-09-19 but never regenerated in the GGUF repos. Ollama's library
24
+ blobs are those files. Ollama never renders it; llama.cpp, vLLM or LM
25
+ Studio serving the file do. **The 0.5B model copies the braces into
26
+ every tool call** (invalid JSON; a strict parser gets 0/35 where the HF
27
+ template gets 22/35); the 1.5B model ignores them. llama-server's parser
28
+ forgives it, vLLM's `json.loads` would not.
29
+ → [`notes/day4-doubled-braces-impact.md`](notes/day4-doubled-braces-impact.md)
30
+ → [`notes/day3-template-command.md`](notes/day3-template-command.md)
31
+ - **Ollama prepends the Modelfile SYSTEM** when a request has none — a
32
+ system prompt your training rows may never have had.
33
+ - **It costs accuracy.** Same GGUF blob in every arm, temperature 0, 40
34
+ cases: Qwen2.5-0.5B gets exact arguments 39/40 with its own template and
35
+ 31/40 with the prompt Ollama builds — every failure an invented
36
+ parameter `amount from_currency`, read off Go's `[amount from_currency
37
+ to_currency]` rendering of `required`. Qwen2.5-1.5B: 40/40 either way on
38
+ this easy set. → [`notes/day2-impact.md`](notes/day2-impact.md)
39
+
40
+ ## Use
41
+
42
+ ```
43
+ uv pip install -e .
44
+ ftgate template --model Qwen/Qwen2.5-0.5B-Instruct \
45
+ --llama http://localhost:8080 \
46
+ --ollama qwen2.5:0.5b-instruct \
47
+ --dataset train.jsonl --sample 20 --diff
48
+ ```
49
+
50
+ `--model` is the HF checkpoint whose tokenizer and chat template the
51
+ trainer used; `--dataset` is your own rows (`messages[, tools]` per line).
52
+ Each runtime's prompt and token ids are compared with what SFT fed the
53
+ model, and every difference is classified: `schema_not_json`,
54
+ `injected_system`, `special_prefix`, `structural`, `spacing`, `tokenizer`.
55
+ Ollama's column is rendered with Ollama's own `template` package (build
56
+ `bin/` once) and cross-checked against the live `prompt_eval_count`.
57
+
58
+ ### `ftgate data` — lint the dataset with the model's own tokenizer and template
59
+
60
+ ```
61
+ ftgate data train.jsonl --model Qwen/Qwen2.5-0.5B-Instruct --max-seq-len 2048 \
62
+ --eval eval.jsonl --fail-on error
63
+ ```
64
+
65
+ Rows in `messages`, ShareGPT, Alpaca or preference (`chosen`/`rejected`)
66
+ shape. Reports what the trainer will silently do to each row: an assistant
67
+ turn that renders to zero target tokens, a conversation cut by
68
+ `max_seq_len` before the answer (trains nothing) or inside it, a row that
69
+ never ends with EOS, a template that raises on the row. Structural checks:
70
+ empty or missing assistant target, role order, tool calls against the
71
+ declared schema (missing required / unknown arguments / undeclared tool /
72
+ `tool_call_id` with no call), `chosen == rejected`, length bias in
73
+ preference pairs, exact duplicates, near-duplicates of the eval set.
74
+ `--format json` for CI; `--fail-on error|warning` sets the exit code.
75
+
76
+ ### `ftgate tools` — does it still call *your* tools, on the backend it will run on?
77
+
78
+ ```
79
+ ftgate tools --tools tools.json --cases cases.jsonl \
80
+ --provider ollama:my-finetune:q4_k_m \
81
+ --provider "openai:m@http://localhost:8080/v1" \
82
+ --min-exact 0.8
83
+ ftgate tools --from-dataset train.jsonl --holdout 50 --provider ollama:my-finetune
84
+ ```
85
+
86
+ Evaluation runs on [promptfoo](https://www.promptfoo.dev/) (installed
87
+ once with `npm install --prefix .pfrunner promptfoo`, or set
88
+ `FTGATE_PROMPTFOO`). ftgate writes the config — your tools, your cases
89
+ (a file, or rows held out of your own training set), one provider per
90
+ arm, temperature 0, one request in flight for local servers — and a
91
+ deterministic judge that reports per case: the right tool, every expected
92
+ argument present and equal (extra optional arguments allowed and counted),
93
+ and two things a generic eval does not separate from "the model was
94
+ wrong": **parser lost** — the model emitted a `<tool_call>` the provider
95
+ did not surface — and **malformed** — the call's JSON does not parse.
96
+ Failure reasons show the produced arguments next to the expected ones.
97
+
98
+ ### In CI, in tests, before commit
99
+
100
+ ```yaml
101
+ # GitHub Actions
102
+ - uses: talhayme/ftgate@main
103
+ with: { dataset: data/train.jsonl, model: Qwen/Qwen2.5-0.5B-Instruct, max-seq-len: "2048" }
104
+ ```
105
+
106
+ ```yaml
107
+ # .pre-commit-config.yaml
108
+ - repo: https://github.com/talhayme/ftgate
109
+ rev: main
110
+ hooks: [{ id: ftgate-data, args: [--fail-on, error] }]
111
+ ```
112
+
113
+ ```python
114
+ # tests/test_data.py
115
+ from ftgate.testing import assert_dataset_clean
116
+
117
+ def test_training_data():
118
+ assert_dataset_clean("data/train.jsonl", model="Qwen/Qwen2.5-0.5B-Instruct", max_seq_len=2048)
119
+ ```
120
+
121
+ or, with the plugin that installs alongside the package,
122
+ `pytest --ftgate-dataset data/train.jsonl --ftgate-model Qwen/Qwen2.5-0.5B-Instruct`.
123
+
124
+ ## Reproduce the findings
125
+
126
+ ```
127
+ uv venv --python 3.12 ~/.venvs/ftgate && uv pip install --python ~/.venvs/ftgate/bin/python torch transformers gguf requests
128
+ # llama-server built from llama.cpp with --jinja support; Ollama ≥ 0.40 running on :11434
129
+ python scripts/hf_side.py # training-side bytes
130
+ python scripts/llama_side.py http://localhost:8089
131
+ python scripts/ollama_side.py # needs bin/ollama-render (see bin/README.md)
132
+ python scripts/day2_eval.py qwen2.5:0.5b-instruct # three-arm accuracy comparison
133
+ ```
134
+
135
+ ## Plan
136
+
137
+ `ftgate template` — the three-sided byte comparison as a command.
138
+ `ftgate data` — a linter for SFT/DPO/tool-call datasets using the target
139
+ model's tokenizer and template. Tool-call evaluation builds on promptfoo's
140
+ `tool-call-f1` / `trajectory:tool-args-match` rather than duplicating them.
141
+
142
+ Apache-2.0.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "ftgate"
3
+ version = "0.1.0"
4
+ description = "Regression checks for small fine-tuned models on tool calling: do runtimes send the bytes the model was trained on?"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "Apache-2.0" }
8
+ authors = [{ name = "Vitalii Bogachev" }]
9
+ keywords = ["fine-tuning", "tool-calling", "ollama", "llama.cpp", "gguf", "evaluation", "dataset", "lint"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Software Development :: Testing",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ ]
18
+ dependencies = ["transformers>=4.45", "requests>=2.31"]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/talhayme/ftgate"
22
+ Repository = "https://github.com/talhayme/ftgate"
23
+ Issues = "https://github.com/talhayme/ftgate/issues"
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest"]
27
+
28
+ [project.scripts]
29
+ ftgate = "ftgate.cli:main"
30
+
31
+ [project.entry-points.pytest11]
32
+ ftgate = "ftgate.pytest_plugin"
33
+
34
+ [build-system]
35
+ requires = ["setuptools>=68"]
36
+ build-backend = "setuptools.build_meta"
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
40
+
41
+ [tool.setuptools.package-data]
42
+ ftgate = ["assets/*.js"]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
ftgate-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """ftgate — do runtimes send the bytes the model was trained on?"""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,77 @@
1
+ // ftgate: judge one tool-calling response against the expected calls.
2
+ //
3
+ // Written once by ftgate, run by promptfoo for every case. It reads the
4
+ // model's output in whatever shape the provider produced — OpenAI
5
+ // tool_calls JSON, a list of function_call items, or raw text with
6
+ // <tool_call> blocks — and reports named scores rather than one pass/fail,
7
+ // so the table can separate "wrong tool", "wrong arguments" and "the
8
+ // call was there but the provider's parser lost it".
9
+ module.exports = (output, context) => {
10
+ const expected = context.vars.__expected_calls; // [{name, arguments}]
11
+ const norm = (v) => {
12
+ if (Array.isArray(v)) return v.map(norm);
13
+ if (v && typeof v === "object") { const o = {}; for (const k of Object.keys(v).sort()) o[k] = norm(v[k]); return o; }
14
+ if (typeof v === "number") return Number(v);
15
+ if (typeof v === "boolean") return v;
16
+ return String(v).trim().toLowerCase();
17
+ };
18
+ // Expected arguments must be present and equal; extra (optional) arguments
19
+ // are allowed and reported separately, so a model that adds unit="celsius"
20
+ // to a weather call is not marked wrong for being thorough.
21
+ const subsetKey = (c, exp) => {
22
+ const got = c.arguments || {}, want = exp.arguments || {};
23
+ const picked = {}; for (const k of Object.keys(want)) picked[k] = got[k];
24
+ return JSON.stringify([c.name, norm(picked)]);
25
+ };
26
+ const wantKey = (e) => JSON.stringify([e.name, norm(e.arguments || {})]);
27
+
28
+ let structured = [];
29
+ let text = typeof output === "string" ? output : JSON.stringify(output);
30
+ const takeCall = (c) => {
31
+ const fn = c.function || c;
32
+ let args = fn.arguments ?? fn.input ?? {};
33
+ if (typeof args === "string") { try { args = JSON.parse(args); } catch (e) { return { name: fn.name, arguments: null, malformed: true }; } }
34
+ return { name: fn.name, arguments: args };
35
+ };
36
+ try {
37
+ const o = typeof output === "string" ? JSON.parse(output) : output;
38
+ const list = Array.isArray(o) ? o : (o && o.tool_calls) ? o.tool_calls : (o && o.name) ? [o] : [];
39
+ structured = list.filter(c => c && (c.function || c.name)).map(takeCall);
40
+ } catch (e) { /* not JSON: raw text */ }
41
+
42
+ let fromText = [];
43
+ const re = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g; let m;
44
+ while ((m = re.exec(text)) !== null) {
45
+ try { const d = JSON.parse(m[1]); fromText.push({ name: d.name, arguments: d.arguments || {} }); }
46
+ catch (e) { fromText.push({ name: null, arguments: null, malformed: true }); }
47
+ }
48
+
49
+ const calls = structured.length ? structured : fromText;
50
+ const parserLost = structured.length === 0 && fromText.length > 0; // the model called; the provider did not surface it
51
+ const malformed = calls.some(c => c.malformed);
52
+ const names = (a) => a.map(c => c.name).sort().join("|");
53
+ const namesOk = names(calls) === names(expected);
54
+ // Pair each expected call with a produced call of the same name (greedy).
55
+ let argsOk = namesOk && !malformed, extra = false;
56
+ if (argsOk) {
57
+ const pool = calls.slice();
58
+ for (const e of expected) {
59
+ const i = pool.findIndex(c => c.name === e.name && subsetKey(c, e) === wantKey(e));
60
+ if (i < 0) { argsOk = false; break; }
61
+ const got = pool[i].arguments || {};
62
+ if (Object.keys(got).some(k => !(k in (e.arguments || {})))) extra = true;
63
+ pool.splice(i, 1);
64
+ }
65
+ }
66
+
67
+ return {
68
+ pass: argsOk,
69
+ score: argsOk ? 1 : namesOk ? 0.5 : 0,
70
+ reason: argsOk ? (extra ? "ok, extra optional arguments" : "exact")
71
+ : !calls.length ? "no call"
72
+ : malformed ? "malformed arguments: " + text.slice(0, 160)
73
+ : !namesOk ? `tools ${names(calls) || "-"} vs expected ${names(expected)}`
74
+ : "arguments differ: got " + JSON.stringify(calls.map(c => c.arguments)) + " expected " + JSON.stringify(expected.map(e => e.arguments)),
75
+ namedScores: { called: calls.length ? 1 : 0, names: namesOk ? 1 : 0, args: argsOk ? 1 : 0, extra_args: extra ? 1 : 0, parser_lost: parserLost ? 1 : 0, malformed: malformed ? 1 : 0 },
76
+ };
77
+ };