lork 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.
lork-0.1.0/LICENSE ADDED
@@ -0,0 +1,182 @@
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 code tracking 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
98
+ notices stating that You have changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright notices, patent notices,
102
+ trademarks, and attribution notices from the Source form of
103
+ the Work, excluding those notices that do not pertain to any
104
+ part of 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 NOTICE text file, except where
109
+ such notices are not included in the Work.
110
+
111
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
112
+ any Contribution intentionally submitted for inclusion in the Work
113
+ by You to the Licensor shall be under the terms and conditions of
114
+ this License, without any additional terms or conditions.
115
+ Notwithstanding the above, nothing herein shall supersede or modify
116
+ the terms of any separate license agreement you may have executed
117
+ with Licensor regarding such Contributions.
118
+
119
+ 6. Trademarks. This License does not grant permission to use the trade
120
+ names, trademarks, service marks, or product names of the Licensor,
121
+ except as required for reasonable and customary use in describing the
122
+ origin of the Work and reproducing the content of the NOTICE file.
123
+
124
+ 7. Disclaimer of Warranty. Unless required by applicable law or
125
+ agreed to in writing, Licensor provides the Work (and each
126
+ Contributor provides its Contributions) on an "AS IS" BASIS,
127
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
128
+ implied, including, without limitation, any warranties or conditions
129
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
130
+ PARTICULAR PURPOSE. You are solely responsible for determining the
131
+ appropriateness of using or redistributing the Work and assume any
132
+ risks associated with Your use of the Work.
133
+
134
+ 8. Limitation of Liability. In no event and under no legal theory,
135
+ whether in tort (including negligence), contract, or otherwise,
136
+ unless required by applicable law (such as deliberate intent) or
137
+ agreed to in writing, shall any Contributor be liable to You for
138
+ damages, including any direct, indirect, special, incidental, or
139
+ consequential damages of any character arising as a result of this
140
+ License or out of the use or inability to use the Work (including
141
+ but not limited to damages for loss of goodwill, work stoppage,
142
+ computer failure or malfunction, or any and all other commercial
143
+ damages or losses), even if such Contributor has been advised of the
144
+ possibility of such damages.
145
+
146
+ 9. Accepting Warranty or Additional Liability. While redistributing
147
+ the Work or Derivative Works thereof, You may choose to offer,
148
+ and charge a fee for, acceptance of support, warranty, indemnity,
149
+ or other liability obligations and/or rights consistent with this
150
+ License. However, in accepting such obligations, You may act only
151
+ on Your own behalf and on Your sole responsibility, not on behalf
152
+ of any other Contributor, and only if You agree to indemnify,
153
+ defend, and hold each Contributor harmless for any liability
154
+ incurred by, or claims asserted against, such Contributor by reason
155
+ of your accepting any such warranty or additional liability.
156
+
157
+ END OF TERMS AND CONDITIONS
158
+
159
+ APPENDIX: How to apply the Apache License to your work.
160
+
161
+ To apply the Apache License to your work, attach the following
162
+ boilerplate notice to the fields enclosed by brackets "[]"
163
+ replaced with your own identifying information. (Don't include
164
+ the brackets!) The text should be enclosed in the appropriate
165
+ comment syntax for the file format. We also recommend that a
166
+ file or class name and description of purpose be included on the
167
+ same "printed page" as the copyright notice for easier
168
+ identification within third-party archives.
169
+
170
+ Copyright 2026 Lork contributors
171
+
172
+ Licensed under the Apache License, Version 2.0 (the "License");
173
+ you may not use this file except in compliance with the License.
174
+ You may obtain a copy of the License at
175
+
176
+ http://www.apache.org/licenses/LICENSE-2.0
177
+
178
+ Unless required by applicable law or agreed to in writing, software
179
+ distributed under the License is distributed on an "AS IS" BASIS,
180
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
181
+ See the License for the specific language governing permissions and
182
+ limitations under the License.
lork-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: lork
3
+ Version: 0.1.0
4
+ Summary: Open-source LoRA fine-tuning service with low-level async execution primitives.
5
+ Author: Murari
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Murari17/lork
8
+ Project-URL: Repository, https://github.com/Murari17/lork
9
+ Project-URL: Documentation, https://github.com/Murari17/lork/tree/main/docs
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: annotated-types==0.8.0
22
+ Requires-Dist: anyio==4.16.0
23
+ Requires-Dist: certifi==2026.11.20
24
+ Requires-Dist: h11==0.16.0
25
+ Requires-Dist: httpcore==1.0.9
26
+ Requires-Dist: httpx==0.28.1
27
+ Requires-Dist: idna==3.20
28
+ Requires-Dist: pydantic==2.14.4
29
+ Requires-Dist: pydantic-core==2.50.5
30
+ Requires-Dist: typing-extensions==4.16.0
31
+ Requires-Dist: typing-inspection==0.4.5
32
+ Provides-Extra: server
33
+ Requires-Dist: accelerate==1.16.0; extra == "server"
34
+ Requires-Dist: annotated-doc==0.0.7; extra == "server"
35
+ Requires-Dist: click==8.5.1; extra == "server"
36
+ Requires-Dist: fastapi==0.165.0; extra == "server"
37
+ Requires-Dist: filelock==4.3.0; extra == "server"
38
+ Requires-Dist: fsspec==2026.9.0; extra == "server"
39
+ Requires-Dist: hf-xet==1.8.0; extra == "server"
40
+ Requires-Dist: httpcore2==2.16.2; extra == "server"
41
+ Requires-Dist: httpx2==2.16.2; extra == "server"
42
+ Requires-Dist: huggingface-hub==2.4.0; extra == "server"
43
+ Requires-Dist: jinja2==3.1.6; extra == "server"
44
+ Requires-Dist: markdown-it-py==4.3.0; extra == "server"
45
+ Requires-Dist: markupsafe==3.0.4; extra == "server"
46
+ Requires-Dist: mdurl==0.1.2; extra == "server"
47
+ Requires-Dist: mpmath==1.3.0; extra == "server"
48
+ Requires-Dist: networkx==3.6.1; extra == "server"
49
+ Requires-Dist: numpy==2.4.6; extra == "server"
50
+ Requires-Dist: opentelemetry-api==1.45.2; extra == "server"
51
+ Requires-Dist: packaging==26.3; extra == "server"
52
+ Requires-Dist: peft==0.22.0; extra == "server"
53
+ Requires-Dist: psutil==7.2.2; extra == "server"
54
+ Requires-Dist: pygments==2.21.0; extra == "server"
55
+ Requires-Dist: pyyaml==6.0.4; extra == "server"
56
+ Requires-Dist: regex==2026.11.19; extra == "server"
57
+ Requires-Dist: rich==15.0.0; extra == "server"
58
+ Requires-Dist: safetensors==0.8.0; extra == "server"
59
+ Requires-Dist: shellingham==1.5.4; extra == "server"
60
+ Requires-Dist: starlette==1.10.0; extra == "server"
61
+ Requires-Dist: sympy==1.14.0; extra == "server"
62
+ Requires-Dist: tokenizers==0.23.3; extra == "server"
63
+ Requires-Dist: torch==2.15.0; extra == "server"
64
+ Requires-Dist: tqdm==4.70.1; extra == "server"
65
+ Requires-Dist: transformers==5.24.0; extra == "server"
66
+ Requires-Dist: truststore==0.10.5; extra == "server"
67
+ Requires-Dist: typer==0.29.2; extra == "server"
68
+ Requires-Dist: uvicorn==0.54.0; extra == "server"
69
+ Provides-Extra: dev
70
+ Requires-Dist: ast-serialize==0.13.1; extra == "dev"
71
+ Requires-Dist: build==1.6.1; extra == "dev"
72
+ Requires-Dist: contourpy==1.3.3; extra == "dev"
73
+ Requires-Dist: cycler==0.12.1; extra == "dev"
74
+ Requires-Dist: fonttools==4.68.0; extra == "dev"
75
+ Requires-Dist: iniconfig==2.3.1; extra == "dev"
76
+ Requires-Dist: kiwisolver==1.5.1; extra == "dev"
77
+ Requires-Dist: librt==0.17.0; extra == "dev"
78
+ Requires-Dist: matplotlib==3.11.2; extra == "dev"
79
+ Requires-Dist: mypy==2.4.1; extra == "dev"
80
+ Requires-Dist: mypy-extensions==1.2.0; extra == "dev"
81
+ Requires-Dist: pathspec==1.1.1; extra == "dev"
82
+ Requires-Dist: pillow==13.0.0; extra == "dev"
83
+ Requires-Dist: pluggy==1.7.0; extra == "dev"
84
+ Requires-Dist: pyparsing==3.3.3; extra == "dev"
85
+ Requires-Dist: pyproject-hooks==1.3.3; extra == "dev"
86
+ Requires-Dist: pytest==9.2.0; extra == "dev"
87
+ Requires-Dist: python-dateutil==4.0.0; extra == "dev"
88
+ Requires-Dist: ruff==0.17.6; extra == "dev"
89
+ Requires-Dist: tzdata==2026.6; extra == "dev"
90
+ Dynamic: license-file
91
+
92
+ # Lork
93
+
94
+ Open-source, self-hosted LoRA fine-tuning execution service built around low-level primitives. **You own the training loop, dataset, and loss function; the server owns execution only.**
95
+
96
+ ## Why Lork?
97
+
98
+ Most fine-tuning frameworks wrap data loading, trainer loops, and loss definitions inside opinionated abstractions that break as soon as you need custom RL/GRPO objectives, non-uniform per-token weighting, or custom gradient accumulation schedules. `lork` exposes only the core execution primitives over an async future-based HTTP API and a lightweight Python SDK (`httpx` + `pydantic`, no `torch` required on the client).
99
+
100
+ ## 60-Second Quickstart
101
+
102
+ ### 1. Install
103
+
104
+ Lightweight Python SDK only (no `torch`, `transformers`, or `peft`):
105
+ ```bash
106
+ pip install lork
107
+ ```
108
+
109
+ Server + trainer runtime (`torch`, `transformers`, `peft`, `fastapi`, `uvicorn`):
110
+ ```bash
111
+ pip install "lork[server]"
112
+ ```
113
+
114
+ ### 2. Start the Server
115
+
116
+ ```bash
117
+ export LORK_API_KEYS="dev-secret-key"
118
+ export LORK_DEVICE="cpu" # or cuda / mps
119
+ uvicorn lork.server.app:create_app --factory --host 127.0.0.1 --port 8000
120
+ ```
121
+
122
+ ### 3. Run Training via the SDK (5 Lines)
123
+
124
+ ```python
125
+ from lork.client import OptimParams, ServiceClient
126
+
127
+ with ServiceClient("http://127.0.0.1:8000", "dev-secret-key") as client, \
128
+ client.create_training_client("Qwen/Qwen2.5-0.5B", 8, 16.0, ["q_proj", "v_proj"]) as tc:
129
+ loss = tc.forward_backward({"input_ids": [[1, 2, 3]], "target_ids": [[2, 3, 4]], "weights": [[1.0, 1.0, 1.0]]}).result().loss
130
+ step = tc.optim_step(OptimParams(lr=5e-4)).result().step
131
+ print(f"step={step} loss={loss:.4f}")
132
+ ```
133
+
134
+ ## Primitives
135
+
136
+ | Primitive | Description |
137
+ | :--- | :--- |
138
+ | `create_training_client(base_model, rank, alpha, target_modules, device, dtype)` | Initializes a dedicated session worker thread with frozen base weights and `fp32` LoRA adapters. |
139
+ | `forward_backward(batch, loss_fn, return_logprobs=True)` | Accumulates weighted gradients across micro-batches without stepping weights; supports `"cross_entropy"` or precomputed per-token advantages, and can omit `logprobs` (`return_logprobs=False`) to shrink wire payloads. |
140
+ | `optim_step(OptimParams(...))` | Normalizes accumulated gradients by window weight, steps `AdamW`, zeros gradients. Idempotent on SDK-generated `step_id`. |
141
+ | `sample(prompts, SampleParams(...))` | Autoregressive generation returning completions, token IDs, and per-token log-probabilities (optional per-call `seed`). |
142
+ | `save_state(name)` / `load_state(name)` | Persists and restores LoRA weights (`safetensors`) and full `AdamW` optimizer state. |
143
+ | `close()` / context manager | Deletes the remote session, frees trainer memory, and empties device caches. |
144
+
145
+ ## Examples
146
+
147
+ Run against a running server (`LORK_BASE_URL` and `LORK_API_KEY`):
148
+
149
+ ```bash
150
+ # Supervised fine-tuning (~30 lines, Qwen/Qwen2.5-0.5B)
151
+ LORK_BASE_URL=http://127.0.0.1:8000 LORK_API_KEY=dev-secret-key python examples/sft.py
152
+
153
+ # Toy GRPO RL task (sample -> reward -> advantages -> forward_backward -> optim_step)
154
+ LORK_BASE_URL=http://127.0.0.1:8000 LORK_API_KEY=dev-secret-key python examples/grpo_toy.py 42
155
+ ```
156
+
157
+ ### Measured 5-Seed Toy GRPO Results (`examples/grpo_toy.py`, `Qwen/Qwen2.5-0.5B`, CPU `fp32`, 12 steps, `GROUP_SIZE=8`)
158
+
159
+ > **Toy task & saturation note**: `examples/grpo_toy.py` is a synthetic toy RL task (`"Reply with only one word (apple or banana):"` with binary reward for `"banana"`). `initial_mean_reward` equals `step_rewards[0]` (the pre-update step-1 group). Once the policy reaches `mean_reward == 1.000` (all 8 samples in the group receive identical reward `1.0`), per-group advantages are identically zero; those **saturated** steps are skipped (`skipped_steps`) rather than running a zero-gradient update.
160
+
161
+ | Base Seed | Initial Mean Reward (Step 1) | Final Mean Reward (Post-Step 12) | Skipped Steps (Saturation) | Per-Step Mean Rewards (`step 1..12`) |
162
+ | :--- | :--- | :--- | :--- | :--- |
163
+ | `42` | `0.125` | `1.000` | `9` | `0.125, 0.500, 0.875, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
164
+ | `43` | `0.125` | `1.000` | `9` | `0.125, 0.750, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
165
+ | `44` | `0.125` | `1.000` | `9` | `0.125, 0.875, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
166
+ | `45` | `0.125` | `1.000` | `8` | `0.125, 0.500, 0.750, 1.000, 1.000, 1.000, 0.875, 1.000, 1.000, 1.000, 1.000, 1.000` |
167
+ | `46` | `0.125` | `1.000` | `9` | `0.125, 0.750, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
168
+
169
+ ## Benchmark (SDK over HTTP vs. Plain `PEFT + AdamW`)
170
+
171
+ Measured via [scripts/benchmark.py](scripts/benchmark.py) on CPU `float32` (`Qwen/Qwen2.5-0.5B`, 20 steps, `batch_size=2`, `seq_len=12`, `480` total tokens — full breakdown in [docs/benchmark.md](docs/benchmark.md), raw data in [docs/benchmark.json](docs/benchmark.json), plot in [docs/loss_curves.png](docs/loss_curves.png)):
172
+ - **Plain `PEFT + AdamW`**: `4.6406 s` (`103.43 tok/s`), `fb` p50/p95 `221.41 / 246.21 ms`, `optim` p50/p95 `3.68 / 4.25 ms`
173
+ - **`lork` SDK (`return_logprobs=True`)**: `4.7333 s` (`101.41 tok/s`, `+1.96%` overhead), `fb` p50/p95 `224.29 / 240.98 ms` (`648.0 B`), `optim` p50/p95 `7.21 / 7.91 ms` (`101.5 B`), max loss deviation `8.39e-05`
174
+ - **`lork` SDK (`return_logprobs=False`)**: `4.7447 s` (`101.17 tok/s`, `+2.19%` overhead), `fb` p50/p95 `224.36 / 238.23 ms` (`118.0 B`), `optim` p50/p95 `7.27 / 8.31 ms` (`101.5 B`), max loss deviation `8.39e-05`
175
+
176
+ ## Docker (CUDA Runtime)
177
+
178
+ ```bash
179
+ export LORK_API_KEYS="your-secret-key"
180
+ docker compose up --build
181
+ ```
182
+
183
+ > Note: `Dockerfile` targets `nvidia/cuda:12.4.1-runtime-ubuntu22.04` as a non-root user (`lork`) with `/cache/huggingface` and `/data/checkpoints` volumes.
184
+
185
+ ## Honest Limits
186
+
187
+ - **Self-hosted / single-tenant**: Static Bearer API keys (`LORK_API_KEYS`) with no multi-tenant isolation or user billing.
188
+ - **No shared base model**: Each active session loads its own base model instance (`~2 GB` RAM per `fp32` `Qwen/Qwen2.5-0.5B` session; `LORK_MAX_SESSIONS` defaults to `2`).
189
+ - **Single-node execution**: One worker thread per session on a single server process (no distributed tensor/data parallelism).
190
+
191
+ ## Docs
192
+
193
+ - [HTTP API Reference](docs/api.md)
194
+ - [Client Retry & Failure Semantics](docs/retries.md)
195
+ - [Benchmark Breakdown](docs/benchmark.md)
196
+ - [Architecture](ARCHITECTURE.md)
197
+ - [GPU Check Script](scripts/gpu_check.py)
198
+ - [Colab Quickstart Notebook](examples/colab_quickstart.ipynb)
lork-0.1.0/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # Lork
2
+
3
+ Open-source, self-hosted LoRA fine-tuning execution service built around low-level primitives. **You own the training loop, dataset, and loss function; the server owns execution only.**
4
+
5
+ ## Why Lork?
6
+
7
+ Most fine-tuning frameworks wrap data loading, trainer loops, and loss definitions inside opinionated abstractions that break as soon as you need custom RL/GRPO objectives, non-uniform per-token weighting, or custom gradient accumulation schedules. `lork` exposes only the core execution primitives over an async future-based HTTP API and a lightweight Python SDK (`httpx` + `pydantic`, no `torch` required on the client).
8
+
9
+ ## 60-Second Quickstart
10
+
11
+ ### 1. Install
12
+
13
+ Lightweight Python SDK only (no `torch`, `transformers`, or `peft`):
14
+ ```bash
15
+ pip install lork
16
+ ```
17
+
18
+ Server + trainer runtime (`torch`, `transformers`, `peft`, `fastapi`, `uvicorn`):
19
+ ```bash
20
+ pip install "lork[server]"
21
+ ```
22
+
23
+ ### 2. Start the Server
24
+
25
+ ```bash
26
+ export LORK_API_KEYS="dev-secret-key"
27
+ export LORK_DEVICE="cpu" # or cuda / mps
28
+ uvicorn lork.server.app:create_app --factory --host 127.0.0.1 --port 8000
29
+ ```
30
+
31
+ ### 3. Run Training via the SDK (5 Lines)
32
+
33
+ ```python
34
+ from lork.client import OptimParams, ServiceClient
35
+
36
+ with ServiceClient("http://127.0.0.1:8000", "dev-secret-key") as client, \
37
+ client.create_training_client("Qwen/Qwen2.5-0.5B", 8, 16.0, ["q_proj", "v_proj"]) as tc:
38
+ loss = tc.forward_backward({"input_ids": [[1, 2, 3]], "target_ids": [[2, 3, 4]], "weights": [[1.0, 1.0, 1.0]]}).result().loss
39
+ step = tc.optim_step(OptimParams(lr=5e-4)).result().step
40
+ print(f"step={step} loss={loss:.4f}")
41
+ ```
42
+
43
+ ## Primitives
44
+
45
+ | Primitive | Description |
46
+ | :--- | :--- |
47
+ | `create_training_client(base_model, rank, alpha, target_modules, device, dtype)` | Initializes a dedicated session worker thread with frozen base weights and `fp32` LoRA adapters. |
48
+ | `forward_backward(batch, loss_fn, return_logprobs=True)` | Accumulates weighted gradients across micro-batches without stepping weights; supports `"cross_entropy"` or precomputed per-token advantages, and can omit `logprobs` (`return_logprobs=False`) to shrink wire payloads. |
49
+ | `optim_step(OptimParams(...))` | Normalizes accumulated gradients by window weight, steps `AdamW`, zeros gradients. Idempotent on SDK-generated `step_id`. |
50
+ | `sample(prompts, SampleParams(...))` | Autoregressive generation returning completions, token IDs, and per-token log-probabilities (optional per-call `seed`). |
51
+ | `save_state(name)` / `load_state(name)` | Persists and restores LoRA weights (`safetensors`) and full `AdamW` optimizer state. |
52
+ | `close()` / context manager | Deletes the remote session, frees trainer memory, and empties device caches. |
53
+
54
+ ## Examples
55
+
56
+ Run against a running server (`LORK_BASE_URL` and `LORK_API_KEY`):
57
+
58
+ ```bash
59
+ # Supervised fine-tuning (~30 lines, Qwen/Qwen2.5-0.5B)
60
+ LORK_BASE_URL=http://127.0.0.1:8000 LORK_API_KEY=dev-secret-key python examples/sft.py
61
+
62
+ # Toy GRPO RL task (sample -> reward -> advantages -> forward_backward -> optim_step)
63
+ LORK_BASE_URL=http://127.0.0.1:8000 LORK_API_KEY=dev-secret-key python examples/grpo_toy.py 42
64
+ ```
65
+
66
+ ### Measured 5-Seed Toy GRPO Results (`examples/grpo_toy.py`, `Qwen/Qwen2.5-0.5B`, CPU `fp32`, 12 steps, `GROUP_SIZE=8`)
67
+
68
+ > **Toy task & saturation note**: `examples/grpo_toy.py` is a synthetic toy RL task (`"Reply with only one word (apple or banana):"` with binary reward for `"banana"`). `initial_mean_reward` equals `step_rewards[0]` (the pre-update step-1 group). Once the policy reaches `mean_reward == 1.000` (all 8 samples in the group receive identical reward `1.0`), per-group advantages are identically zero; those **saturated** steps are skipped (`skipped_steps`) rather than running a zero-gradient update.
69
+
70
+ | Base Seed | Initial Mean Reward (Step 1) | Final Mean Reward (Post-Step 12) | Skipped Steps (Saturation) | Per-Step Mean Rewards (`step 1..12`) |
71
+ | :--- | :--- | :--- | :--- | :--- |
72
+ | `42` | `0.125` | `1.000` | `9` | `0.125, 0.500, 0.875, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
73
+ | `43` | `0.125` | `1.000` | `9` | `0.125, 0.750, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
74
+ | `44` | `0.125` | `1.000` | `9` | `0.125, 0.875, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
75
+ | `45` | `0.125` | `1.000` | `8` | `0.125, 0.500, 0.750, 1.000, 1.000, 1.000, 0.875, 1.000, 1.000, 1.000, 1.000, 1.000` |
76
+ | `46` | `0.125` | `1.000` | `9` | `0.125, 0.750, 0.750, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000` |
77
+
78
+ ## Benchmark (SDK over HTTP vs. Plain `PEFT + AdamW`)
79
+
80
+ Measured via [scripts/benchmark.py](scripts/benchmark.py) on CPU `float32` (`Qwen/Qwen2.5-0.5B`, 20 steps, `batch_size=2`, `seq_len=12`, `480` total tokens — full breakdown in [docs/benchmark.md](docs/benchmark.md), raw data in [docs/benchmark.json](docs/benchmark.json), plot in [docs/loss_curves.png](docs/loss_curves.png)):
81
+ - **Plain `PEFT + AdamW`**: `4.6406 s` (`103.43 tok/s`), `fb` p50/p95 `221.41 / 246.21 ms`, `optim` p50/p95 `3.68 / 4.25 ms`
82
+ - **`lork` SDK (`return_logprobs=True`)**: `4.7333 s` (`101.41 tok/s`, `+1.96%` overhead), `fb` p50/p95 `224.29 / 240.98 ms` (`648.0 B`), `optim` p50/p95 `7.21 / 7.91 ms` (`101.5 B`), max loss deviation `8.39e-05`
83
+ - **`lork` SDK (`return_logprobs=False`)**: `4.7447 s` (`101.17 tok/s`, `+2.19%` overhead), `fb` p50/p95 `224.36 / 238.23 ms` (`118.0 B`), `optim` p50/p95 `7.27 / 8.31 ms` (`101.5 B`), max loss deviation `8.39e-05`
84
+
85
+ ## Docker (CUDA Runtime)
86
+
87
+ ```bash
88
+ export LORK_API_KEYS="your-secret-key"
89
+ docker compose up --build
90
+ ```
91
+
92
+ > Note: `Dockerfile` targets `nvidia/cuda:12.4.1-runtime-ubuntu22.04` as a non-root user (`lork`) with `/cache/huggingface` and `/data/checkpoints` volumes.
93
+
94
+ ## Honest Limits
95
+
96
+ - **Self-hosted / single-tenant**: Static Bearer API keys (`LORK_API_KEYS`) with no multi-tenant isolation or user billing.
97
+ - **No shared base model**: Each active session loads its own base model instance (`~2 GB` RAM per `fp32` `Qwen/Qwen2.5-0.5B` session; `LORK_MAX_SESSIONS` defaults to `2`).
98
+ - **Single-node execution**: One worker thread per session on a single server process (no distributed tensor/data parallelism).
99
+
100
+ ## Docs
101
+
102
+ - [HTTP API Reference](docs/api.md)
103
+ - [Client Retry & Failure Semantics](docs/retries.md)
104
+ - [Benchmark Breakdown](docs/benchmark.md)
105
+ - [Architecture](ARCHITECTURE.md)
106
+ - [GPU Check Script](scripts/gpu_check.py)
107
+ - [Colab Quickstart Notebook](examples/colab_quickstart.ipynb)
@@ -0,0 +1,133 @@
1
+ [build-system]
2
+ requires = ["setuptools==84.2.1"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lork"
7
+ version = "0.1.0"
8
+ description = "Open-source LoRA fine-tuning service with low-level async execution primitives."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "Murari" }]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Intended Audience :: Science/Research",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = [
24
+ "annotated-types==0.8.0",
25
+ "anyio==4.16.0",
26
+ "certifi==2026.11.20",
27
+ "h11==0.16.0",
28
+ "httpcore==1.0.9",
29
+ "httpx==0.28.1",
30
+ "idna==3.20",
31
+ "pydantic==2.14.4",
32
+ "pydantic-core==2.50.5",
33
+ "typing-extensions==4.16.0",
34
+ "typing-inspection==0.4.5",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/Murari17/lork"
39
+ Repository = "https://github.com/Murari17/lork"
40
+ Documentation = "https://github.com/Murari17/lork/tree/main/docs"
41
+
42
+ [project.optional-dependencies]
43
+ server = [
44
+ "accelerate==1.16.0",
45
+ "annotated-doc==0.0.7",
46
+ "click==8.5.1",
47
+ "fastapi==0.165.0",
48
+ "filelock==4.3.0",
49
+ "fsspec==2026.9.0",
50
+ "hf-xet==1.8.0",
51
+ "httpcore2==2.16.2",
52
+ "httpx2==2.16.2",
53
+ "huggingface-hub==2.4.0",
54
+ "jinja2==3.1.6",
55
+ "markdown-it-py==4.3.0",
56
+ "markupsafe==3.0.4",
57
+ "mdurl==0.1.2",
58
+ "mpmath==1.3.0",
59
+ "networkx==3.6.1",
60
+ "numpy==2.4.6",
61
+ "opentelemetry-api==1.45.2",
62
+ "packaging==26.3",
63
+ "peft==0.22.0",
64
+ "psutil==7.2.2",
65
+ "pygments==2.21.0",
66
+ "pyyaml==6.0.4",
67
+ "regex==2026.11.19",
68
+ "rich==15.0.0",
69
+ "safetensors==0.8.0",
70
+ "shellingham==1.5.4",
71
+ "starlette==1.10.0",
72
+ "sympy==1.14.0",
73
+ "tokenizers==0.23.3",
74
+ "torch==2.15.0",
75
+ "tqdm==4.70.1",
76
+ "transformers==5.24.0",
77
+ "truststore==0.10.5",
78
+ "typer==0.29.2",
79
+ "uvicorn==0.54.0",
80
+ ]
81
+ dev = [
82
+ "ast-serialize==0.13.1",
83
+ "build==1.6.1",
84
+ "contourpy==1.3.3",
85
+ "cycler==0.12.1",
86
+ "fonttools==4.68.0",
87
+ "iniconfig==2.3.1",
88
+ "kiwisolver==1.5.1",
89
+ "librt==0.17.0",
90
+ "matplotlib==3.11.2",
91
+ "mypy==2.4.1",
92
+ "mypy-extensions==1.2.0",
93
+ "pathspec==1.1.1",
94
+ "pillow==13.0.0",
95
+ "pluggy==1.7.0",
96
+ "pyparsing==3.3.3",
97
+ "pyproject-hooks==1.3.3",
98
+ "pytest==9.2.0",
99
+ "python-dateutil==4.0.0",
100
+ "ruff==0.17.6",
101
+ "tzdata==2026.6",
102
+ ]
103
+
104
+ [tool.setuptools.packages.find]
105
+ where = ["src"]
106
+
107
+ [tool.setuptools.package-data]
108
+ lork = ["py.typed"]
109
+ "lork.client" = ["py.typed"]
110
+
111
+ [tool.ruff]
112
+ target-version = "py311"
113
+ line-length = 100
114
+ src = ["src", "tests", "examples", "scripts"]
115
+
116
+ [tool.ruff.lint]
117
+ select = ["E", "F", "I", "UP", "B", "SIM"]
118
+
119
+ [tool.mypy]
120
+ python_version = "3.11"
121
+ strict = true
122
+ mypy_path = "src"
123
+ packages = ["lork"]
124
+ ignore_missing_imports = true
125
+
126
+ [tool.pytest.ini_options]
127
+ testpaths = ["tests"]
128
+ pythonpath = ["."]
129
+ addopts = "-ra"
130
+ markers = [
131
+ "slow: slow integration or RL tests",
132
+ "gpu: CUDA GPU tests (skipped when CUDA is unavailable)",
133
+ ]
lork-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,37 @@
1
+ """lork: Open-source low-level LoRA fine-tuning primitives and client SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from lork.wire import (
8
+ OptimParams,
9
+ SampleParams,
10
+ TrainerInitConfig,
11
+ WireBatch,
12
+ )
13
+
14
+ if TYPE_CHECKING:
15
+ from lork.schemas import ForwardBackwardBatch
16
+ from lork.trainer import LoraTrainer
17
+
18
+ __all__ = [
19
+ "ForwardBackwardBatch",
20
+ "LoraTrainer",
21
+ "OptimParams",
22
+ "SampleParams",
23
+ "TrainerInitConfig",
24
+ "WireBatch",
25
+ ]
26
+
27
+
28
+ def __getattr__(name: str) -> Any:
29
+ if name == "LoraTrainer":
30
+ from lork.trainer import LoraTrainer
31
+
32
+ return LoraTrainer
33
+ if name == "ForwardBackwardBatch":
34
+ from lork.schemas import ForwardBackwardBatch
35
+
36
+ return ForwardBackwardBatch
37
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")