Run this model with HF Jobs
Run AIXF/sbNeo on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/AIXF/sbNeo. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/AIXF/sbNeo on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/AIXF/sbNeo. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/AIXF/sbNeo. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use AIXF/sbNeo with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use AIXF/sbNeo with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.5-4B") model = PeftModel.from_pretrained(base_model, "AIXF/sbNeo") - Notebooks
- Google Colab
- Kaggle
Publish sbNeo Qwen3.5-4B style LoRA with training metrics and loading example
Browse filesFiles changed (11)
- LICENSEAdded+202
- README.mdAdded+73
- SHA256SUMSAdded+10
- adapter_config.jsonAdded+49
- adapter_model.safetensorsAdded+3
- dataset_summary.jsonAdded+44
- prepare_dataset.pyAdded+159
- requirements.txtAdded+7
- train_modal.pyAdded+418
- training_config.jsonAdded+34
- training_results.jsonAdded+21
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273---language: zhlicense: apache-2.0library_name: peftpipeline_tag: text-generationbase_model: Qwen/Qwen3.5-4Bbase_model_relation: adaptertags:- lora- qwen3_5- conversational- style-transfer---
# sbNeo · Qwen3.5-4B LoRA
学习 LINUX DO 用户 Neo 的简短、随意中文表达风格的**非官方 LoRA 适配器**。由 AIXF 训练发布,不是 Neo 本人或 LINUX DO 官方提供的模型,也不代表该用户的真实身份、观点或认可。
这是约 40 MB 的独立适配器,需与 `Qwen/Qwen3.5-4B` 一起加载,不能作为完整底模单独运行。权重采用 Apache-2.0;论坛原文不随本仓库发布,这一许可不声明对论坛原文的再许可。
## 数据与训练
来源:https://linux.do/u/neo/activity 。处理约 8,400 条活动行后停止;去重并排除系统提示后有 7,305 条可见发言。排除 794 条未展开摘要,移除其他作者引用,并排除 5 条空正文后,使用 6,506 条样本:训练 5,204、验证 651、测试 651。
输入只包含真实主题标题和类别,**没有此前楼层上下文,没有虚构问答**。页面直接显示的正文未逐条与主题原文核对,不能保证全部完整;话题首帖未采到。主题在各集合间隔离,至少 20 字的相同答案对应主题也分到同一集合;短表达保留原始出现频次。
Modal L4,BF16 LoRA SFT,完整一轮。rank 8、alpha 16、dropout 0.05、学习率 1e-4;仅计算助手答案损失。训练约 93.14 分钟,5,204 次更新,9,961,472 个可训练参数。最大序列 1,024 token,答案上限 512 token。
## 评估与限制
| 指标 | 损失 ||---|---:|| 底模验证 | 5.611190 || 最终/最佳验证,第 5,204 步 | 3.849142 || 独立测试,651 条 | 3.850969 |
这些指标只反映预测留出论坛回复的难度,不是通用能力、风格相似度或事实准确性的评估。初次实际两轮对话测试中,完整适配强度的模型对用户刚告知的水果偏好答非所问;因此不能保证切题、记忆准确或可靠回答。也没有经过通用基准评测。它可能生成论坛表情文本标记,例如 `:tieba_025:`。
## 加载示例
安装 `requirements.txt` 中的模型依赖,在支持 BF16 的 CUDA GPU 上运行:
```pythonimport torchfrom transformers import AutoModelForImageTextToText, AutoTokenizerfrom peft import PeftModel
base_id = "Qwen/Qwen3.5-4B"revision = "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"tokenizer = AutoTokenizer.from_pretrained(base_id, revision=revision)base = AutoModelForImageTextToText.from_pretrained( base_id, revision=revision, dtype=torch.bfloat16, device_map={"": 0}, attn_implementation="sdpa",)model = PeftModel.from_pretrained(base, "AIXF/sbNeo").eval()messages = [ {"role": "system", "content": "直接回答用户的问题,用简短、随意的中文表达。不要冒充 Neo。"}, {"role": "user", "content": "我做了一个小项目,但不知道怎么介绍,你有什么建议?"},]prompt = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False,)inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to("cuda")with torch.inference_mode(): result = model.generate( **inputs, max_new_tokens=128, do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.1, eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"), )print(tokenizer.decode(result[0, inputs.input_ids.shape[1]:], skip_special_tokens=True))```
示例是与已部署服务相同的加载方式,但未对这段仓库示例单独进行 GPU 运行验证。训练脚本和数据整理脚本可供检查流程;原始语料不在仓库,因此仓库本身不是可独立重现的完整训练数据包。`train_modal.py` 需要本地 Modal 登录和准备好的 `data/`、`manifest.json`,运行会消耗计算额度。12345678910cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE51bb385f03c78de6ba3d3eb8ffe3cabdff0495937f45812917f04c5e1ca1a477 README.md3cf83c2400678815e9593dd0a30aa781439bea50ca3c880365ad2512ae78c932 adapter_config.json9ee6494563654dfc132a661b549e73e1b200e55fcb215a2f2ac1de62d598f504 adapter_model.safetensors126ffc526c5556e1a2b727296e2ec46e6f5e522e7823c0b7d380863eab68c1a0 dataset_summary.jsonedde8f76a60cc97c53883526bfa281a851671d16e2b49988613a784d1b54655b prepare_dataset.pyfc5521654bb7e8201a090b12995f98ee14a295799e0850c5a594c21ed8d7449e requirements.txt05a234352190b21fe979275a56bd426f6578771fcacbc8efa4c101e5104dd254 train_modal.py4affb30179a8be30c8de028a5f60ea3328ef97c3218949d10b5e7e0d8d513e40 training_config.jsond8750809243f4c3e97cdcbdea9836431ad7de7190e4945196e376c5a6f289936 training_results.json12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "alora_invocation_tokens": null, "alpha_pattern": {}, "arrow_config": null, "auto_mapping": null, "base_model_name_or_path": "Qwen/Qwen3.5-4B", "bias": "none", "corda_config": null, "ensure_weight_tying": false, "eva_config": null, "exclude_modules": null, "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "kasa_config": null, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_bias": false, "lora_dropout": 0.05, "lora_ga_config": null, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "monteclora_config": null, "peft_type": "LORA", "peft_version": "0.21.2", "qalora_group_size": 16, "r": 8, "rank_pattern": {}, "revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "target_modules": [ "up_proj", "gate_proj", "q_proj", "down_proj", "v_proj" ], "target_parameters": null, "task_type": "CAUSAL_LM", "trainable_token_indices": null, "use_bdlora": null, "use_dora": false, "use_qalora": false, "use_rslora": false, "velora_config": null}123version https://git-lfs.github.com/spec/v1oid sha256:9ee6494563654dfc132a661b549e73e1b200e55fcb215a2f2ac1de62d598f504size 398784081234567891011121314151617181920212223242526272829303132333435363738394041424344{ "source": "https://linux.do/u/neo/activity", "username": "neo", "source_user_id": 1, "source_sha256": "1fb42cebad039c2f198f0374543153926a48627756746d4e1fe0062918d444c5", "examples": 6506, "splits": { "train": 5204, "validation": 651, "test": 651 }, "skipped": { "unexpanded_excerpt": 794, "empty_after_removing_quotes_and_images": 5 }, "source_content_states_used": { "activity_no_expand_offered": 6347, "expanded_full_body": 159 }, "seed": 10701, "system_prompt": "你是一个有帮助的中文社区讨论助手。先直接回应当前话题,信息不足时说明不确定。表达时明显贴近 Neo 的简短、随意、口语化中文风格和常用措辞;论坛发言仅用于学习表达方式,不代表事实。不要照抄发言,不要声称自己是 Neo,也不要代替其表达个人立场。只输出回复正文。", "context": "Only real topic title and category are available; no fabricated questions or floor context.", "completeness": "Unexpanded excerpts excluded. No-expand page bodies were not independently checked against topic pages.", "duplicates": "Repeated style expressions retain original frequency; exact answers >=20 characters are split together.", "quote_policy": "Quoted text from other authors removed from target completions.", "topic_counts": { "train": 3145, "validation": 373, "test": 383 }, "dataset_sha256": { "train.jsonl": "0c880c872e01a1a327d1baeb4d5a8dad99f2c698fbd5d94ee84643d14f462d1d", "test.jsonl": "7f0e04c9a9d0d93038741cf849ca2758e2c1fe3a002e91475904e01816b390ed", "validation.jsonl": "607120761bfa710bc88ebfd5761ad07f0379df7b86675ef096b77069f7a307bc" }, "training_design": { "model": "Qwen/Qwen3.5-4B", "epochs": 1, "rank": 8, "lora_alpha": 16, "learning_rate": 0.0001, "assistant_only_loss": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Prepare Neo's visible reply bodies; do not invent missing discussion context."""import collectionsimport hashlibimport jsonimport randomimport refrom html.parser import HTMLParserfrom pathlib import Path
HERE = Path(__file__).resolve().parentSOURCE = HERE.parent / 'linuxdo-neo' / 'utterances.jsonl'SEED = 10701SYSTEM = ( '你是一个有帮助的中文社区讨论助手。先直接回应当前话题,信息不足时说明不确定。' '表达时明显贴近 Neo 的简短、随意、口语化中文风格和常用措辞;' '论坛发言仅用于学习表达方式,不代表事实。不要照抄发言,' '不要声称自己是 Neo,也不要代替其表达个人立场。只输出回复正文。')
class BodyParser(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.parts, self.stack, self.suppressed = [], [], 0
def handle_starttag(self, tag, attrs): attrs = dict(attrs) drop = tag in {'blockquote', 'script', 'style'} or ( tag == 'aside' and 'quote' in attrs.get('class', '').split() ) void = tag in {'br', 'img', 'hr', 'input', 'source', 'wbr', 'meta', 'link'} if not void: self.stack.append((tag, drop)) self.suppressed += int(drop) if self.suppressed: return if tag in {'br', 'p', 'div', 'li', 'pre', 'hr'}: self.parts.append('\n') if tag == 'img' and ( 'emoji' in attrs.get('class', '') or '/emoji/' in attrs.get('src', '') ): self.parts.append(attrs.get('alt', ''))
def handle_endtag(self, tag): for index in range(len(self.stack) - 1, -1, -1): if self.stack[index][0] == tag: removed = self.stack[index:] del self.stack[index:] self.suppressed -= sum(int(drop) for _, drop in removed) break if not self.suppressed and tag in {'p', 'div', 'li', 'pre'}: self.parts.append('\n')
def handle_data(self, data): if not self.suppressed: self.parts.append(data)
def clean(text): text = str(text or '').replace('\u200b', '').strip() text = re.sub(r'\b(?:sk|hf)_[A-Za-z0-9_-]{12,}\b', '[令牌已隐藏]', text) text = re.sub(r'<\|[^|]{1,80}\|>', '〔论坛文本特殊标记〕', text) text = re.sub(r'[ \t]+', ' ', text) return re.sub(r'\n{3,}', '\n\n', text).strip()
def main(): data = HERE / 'data' data.mkdir(parents=True, exist_ok=True) rows, skipped = [], collections.Counter() states = collections.Counter() for line in SOURCE.open(encoding='utf-8'): row = json.loads(line) if row.get('user_id') != 1 or row.get('activity_system_note'): skipped['not_target_body'] += 1 continue if row.get('content_state') == 'unexpanded_excerpt': skipped['unexpanded_excerpt'] += 1 continue html = row.get('cooked_html', '') if re.search(r'<(?:div|p|span|a|img|aside|blockquote|br|pre|code|ul|li)\b', html): parser = BodyParser() parser.feed(html) answer = clean(''.join(parser.parts)) else: answer = clean(row.get('text', '')) if not answer: skipped['empty_after_removing_quotes_and_images'] += 1 continue title = clean(row.get('title', '')) if not title or not row.get('topic_id'): skipped['missing_real_topic'] += 1 continue states[row.get('content_state')] += 1 rows.append({ 'user': '请围绕下面主题发表一条社区回复,直接输出回复正文。\n' f"版块:{clean(row.get('category', '社区'))}\n主题:{title}", 'assistant': answer, 'post_id': row['post_id'], 'topic_id': row['topic_id'], 'source_url': row.get('url'), 'source_content_state': row.get('content_state'), })
# Topic-isolated splits. Identical longer replies also connect topics to # avoid placing the same substantive answer in both train and evaluation. parents = {row['topic_id']: row['topic_id'] for row in rows} def find(value): while parents[value] != value: parents[value] = parents[parents[value]] value = parents[value] return value answers = {} for row in rows: normalized = re.sub(r'\s+', '', row['assistant']) if len(normalized) >= 20: if normalized in answers: parents[find(row['topic_id'])] = find(answers[normalized]) else: answers[normalized] = row['topic_id'] groups = collections.defaultdict(list) for row in rows: groups[find(row['topic_id'])].append(row) keys = sorted(groups) random.Random(SEED).shuffle(keys) counts = {'train': 0, 'validation': 0, 'test': 0} splits = {name: [] for name in counts} targets = {'train': .8 * len(rows), 'validation': .1 * len(rows), 'test': .1 * len(rows)} for key in keys: name = min(counts, key=lambda name: counts[name] / max(targets[name], 1)) splits[name].extend(groups[key]) counts[name] += len(groups[key]) for name, values in splits.items(): if not values: raise RuntimeError(f'Empty split: {name}') with (data / f'{name}.jsonl').open('w', encoding='utf-8') as file: for row in values: file.write(json.dumps(row, ensure_ascii=False) + '\n') topic_sets = {name: {r['topic_id'] for r in values} for name, values in splits.items()} for left, right in [('train', 'validation'), ('train', 'test'), ('validation', 'test')]: assert not topic_sets[left] & topic_sets[right] manifest = { 'source': 'https://linux.do/u/neo/activity', 'username': 'neo', 'source_user_id': 1, 'source_sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), 'examples': len(rows), 'splits': counts, 'skipped': dict(skipped), 'source_content_states_used': dict(states), 'seed': SEED, 'system_prompt': SYSTEM, 'context': 'Only real topic title and category are available; no fabricated questions or floor context.', 'completeness': 'Unexpanded excerpts excluded. No-expand page bodies were not independently checked against topic pages.', 'duplicates': 'Repeated style expressions retain original frequency; exact answers >=20 characters are split together.', 'quote_policy': 'Quoted text from other authors removed from target completions.', 'topic_counts': {name: len(values) for name, values in topic_sets.items()}, 'dataset_sha256': {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in data.glob('*.jsonl')}, 'training_design': {'model': 'Qwen/Qwen3.5-4B', 'epochs': 1, 'rank': 8, 'lora_alpha': 16, 'learning_rate': 1e-4, 'assistant_only_loss': True}, } (HERE / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n') print(json.dumps({key: manifest[key] for key in ['examples', 'splits', 'skipped', 'topic_counts']}, ensure_ascii=False))
if __name__ == '__main__': main()1234567torch==2.8.0transformers==5.18.0peft==0.21.2accelerate==1.10.1safetensors==0.8.0huggingface_hub==1.33.0modal==1.6.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418"""Train a high-strength style LoRA on a topic-disjoint Modal L4 run."""from __future__ import annotations
import jsonimport modalfrom pathlib import Path
MODEL_ID = "Qwen/Qwen3.5-4B"MODEL_REVISION = "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"APP_NAME = "linuxdo-neo-qwen35-style-training"VOLUME_NAME = "linuxdo-neo-qwen35-style-adapter"HERE = Path(__file__).resolve().parentDATA_DIR = HERE / "data"MANIFEST = HERE / "manifest.json"
app = modal.App(APP_NAME)results = modal.Volume.from_name(VOLUME_NAME, create_if_missing=True)
image = ( modal.Image.debian_slim(python_version="3.12") .pip_install( "torch==2.8.0", "transformers==5.18.0", "peft==0.21.2", "accelerate==1.10.1", "safetensors==0.8.0", "huggingface_hub==1.33.0", "numpy<3", ) .env({ "HF_HOME": "/tmp/huggingface", "HF_HUB_DISABLE_TELEMETRY": "1", "TOKENIZERS_PARALLELISM": "false", "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", }) .add_local_dir(str(DATA_DIR), remote_path="/data") .add_local_file(str(MANIFEST), remote_path="/data/manifest.json"))
@app.function( image=image, gpu="L4", cpu=(4, 4), memory=(32768, 32768), timeout=4 * 60 * 60, max_containers=1, volumes={"/results": results},)def train(run_id: str): import gc import hashlib import math import os import random import re import shutil import time from datetime import datetime, timezone from pathlib import Path
import numpy as np import torch from huggingface_hub import snapshot_download from peft import LoraConfig, get_peft_model from transformers import AutoModelForImageTextToText, AutoTokenizer, get_linear_schedule_with_warmup
torch.manual_seed(10701) random.seed(10701) np.random.seed(10701) torch.backends.cuda.matmul.allow_tf32 = True if not torch.cuda.is_available(): raise RuntimeError("Modal L4 CUDA device is unavailable") if not torch.cuda.is_bf16_supported(): raise RuntimeError("The selected GPU does not support BF16")
root = Path("/results") / run_id root.mkdir(parents=True, exist_ok=False) started = time.time() metrics_path = root / "metrics.jsonl" status_path = root / "status.json" system = ( "你是一个有帮助的社区讨论助手。先准确、直接地回应当前话题,信息不足时说明不确定。" "表达时明显贴近 Neo 简短、随意、口语化的中文风格和常用措辞;发言示例只用于学习表达方式,不代表事实。" "不要照抄示例,也不要声称自己是 Neo 或代替其表达个人立场。只输出回复正文。" ) max_prompt_tokens = 512 max_answer_tokens = 512 max_sequence_length = 1024
def write_status(stage: str, **extra): state = { "run_id": run_id, "stage": stage, "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "updated_at": datetime.now(timezone.utc).isoformat(), "elapsed_seconds": round(time.time() - started, 2), **extra, } temp = status_path.with_suffix(".tmp") temp.write_text(json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") temp.replace(status_path) return state
def log_metric(kind: str, **values): record = { "kind": kind, "elapsed_seconds": round(time.time() - started, 2), **values, } with metrics_path.open("a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n")
def append_training_message(user_text: str, answer: str, tokenizer): # The chat template gives an exact assistant-generation prefix. The # loss mask below excludes that prefix, so only style-bearing answers # can update the adapter. user_text = re.sub(r"<\|[^|]{1,80}\|>", "〔论坛文本中的特殊标记〕", user_text) answer = re.sub(r"<\|[^|]{1,80}\|>", "〔论坛文本中的特殊标记〕", answer) user_lines = user_text.splitlines() messages = [ {"role": "system", "content": system}, {"role": "user", "content": user_text}, ] prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) # Keep the task, topic and most recent context if a record exceeds # the prompt budget. Earlier discussion lines are discarded first. if len(prefix) > max_prompt_tokens: headers = user_lines[:3] body = user_lines[3:] while body and len(prefix) > max_prompt_tokens: body.pop(0) messages[1]["content"] = "\n".join(headers + body) prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) if len(prefix) > max_prompt_tokens: clipped = "\n".join(headers)[:600] messages[1]["content"] = clipped prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) answer_ids = tokenizer(answer, add_special_tokens=False)["input_ids"] end_id = tokenizer.convert_tokens_to_ids("<|im_end|>") answer_ids = answer_ids[:max_answer_tokens] full = list(prefix) + list(answer_ids) + [end_id] if len(full) > max_sequence_length: raise ValueError("Encoded sequence exceeded configured maximum") labels = [-100] * len(prefix) + list(answer_ids) + [end_id] if not answer_ids: return None return full, labels, len(answer_ids) + 1
try: write_status("downloading_model") print(f"Downloading pinned public model {MODEL_ID}@{MODEL_REVISION}", flush=True) model_dir = snapshot_download( repo_id=MODEL_ID, revision=MODEL_REVISION, local_dir="/tmp/qwen35-base", allow_patterns=["*.json", "*.safetensors", "*.jinja"], ) print("Model snapshot ready", flush=True)
tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True, trust_remote_code=False) tokenizer.padding_side = "right" model = AutoModelForImageTextToText.from_pretrained( model_dir, dtype=torch.bfloat16, low_cpu_mem_usage=True, device_map={"": 0}, attn_implementation="sdpa", trust_remote_code=False, ) model.config.use_cache = False if hasattr(model.config, "text_config"): model.config.text_config.use_cache = False model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads()
lora = LoraConfig( r=8, lora_alpha=16, target_modules=["q_proj", "v_proj", "gate_proj", "up_proj", "down_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, lora) trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) total = sum(p.numel() for p in model.parameters()) model.print_trainable_parameters()
def load_split(name: str): rows = [] path = Path("/data") / f"{name}.jsonl" for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue row = json.loads(line) encoded = append_training_message(row["user"], row["assistant"], tokenizer) if encoded is not None: ids, labels, answer_count = encoded rows.append((ids, labels, answer_count)) return rows
train_data = load_split("train") valid_data = load_split("validation") test_data = load_split("test") if not train_data or not valid_data or not test_data: raise RuntimeError("A training or evaluation split is empty") print( f"Prepared examples: train={len(train_data)}, validation={len(valid_data)}, test={len(test_data)}", flush=True, ) config = { "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "gpu": "L4", "cpu_cores": 4, "host_memory_gib": 32, "method": "BF16 LoRA SFT", "epochs_target": 1, "optimizer": "AdamW", "learning_rate": 1e-4, "weight_decay": 0.01, "warmup_ratio": 0.03, "batch_size": 1, "gradient_checkpointing": True, "rank": 8, "lora_alpha": 16, "lora_dropout": 0.05, "target_modules": ["q_proj", "v_proj", "gate_proj", "up_proj", "down_proj"], "max_sequence_length": max_sequence_length, "max_prompt_tokens": max_prompt_tokens, "max_answer_tokens": max_answer_tokens, "loss_mask": "prompt tokens ignored; assistant answer and end token trained", "duplicate_answers": "preserved at full frequency", "checkpoint_selection": "final adapter after all training examples; validation-best checkpoint also retained", "trainable_parameters": trainable, "total_parameters": total, "dataset_manifest_sha256": hashlib.sha256(Path("/data/manifest.json").read_bytes()).hexdigest(), } (root / "training-config.json").write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") shutil.copy2("/data/manifest.json", root / "dataset-manifest.json")
optimizer = torch.optim.AdamW( (p for p in model.parameters() if p.requires_grad), lr=config["learning_rate"], weight_decay=config["weight_decay"], ) steps_total = len(train_data) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=max(5, int(steps_total * config["warmup_ratio"])), num_training_steps=steps_total, )
def tensors(encoded): ids, labels, _ = encoded return ( torch.tensor([ids], dtype=torch.long, device="cuda"), torch.tensor([labels], dtype=torch.long, device="cuda"), )
@torch.no_grad() def evaluate(data, label): model.eval() weighted_loss = 0.0 target_tokens = 0 for encoded in data: ids, labels = tensors(encoded) loss = model(input_ids=ids, attention_mask=torch.ones_like(ids), labels=labels).loss weight = encoded[2] weighted_loss += float(loss.detach().float().item()) * weight target_tokens += weight model.train() return weighted_loss / max(target_tokens, 1)
train_order = list(range(len(train_data))) random.Random(10701).shuffle(train_order) eval_every = max(100, math.ceil(steps_total / 5)) eval_every = min(eval_every, steps_total) baseline_loss = evaluate(valid_data, "validation_baseline") log_metric("validation_baseline", iteration=0, loss=baseline_loss) print(f"Baseline validation loss={baseline_loss:.4f}", flush=True) best_loss = baseline_loss best_step = 0 model.save_pretrained(root / "best-adapter", safe_serialization=True) results.commit() optimizer.zero_grad(set_to_none=True) model.train() write_status( "training", current_iteration=0, total_iterations=steps_total, validation_examples=len(valid_data), test_examples=len(test_data), trainable_parameters=trainable, ) print(f"Starting one pass over {steps_total} examples; validation every {eval_every} updates", flush=True)
for step, index in enumerate(train_order, start=1): if time.time() - started > 3 * 60 * 60: model.save_pretrained(root / "interrupted-adapter", safe_serialization=True) results.commit() raise RuntimeError("Three-hour runtime guard reached; partial adapter saved, no automatic restart") ids, labels = tensors(train_data[index]) with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=ids, attention_mask=torch.ones_like(ids), labels=labels).loss loss.backward() torch.nn.utils.clip_grad_norm_((p for p in model.parameters() if p.requires_grad), 1.0) optimizer.step() scheduler.step() optimizer.zero_grad(set_to_none=True)
if step == 1 or step % 50 == 0 or step == steps_total: train_loss = float(loss.detach().float().item()) log_metric("train", iteration=step, total_iterations=steps_total, loss=train_loss, learning_rate=scheduler.get_last_lr()[0]) write_status("training", current_iteration=step, total_iterations=steps_total, train_loss=train_loss) print(f"step {step}/{steps_total} train_loss={train_loss:.4f}", flush=True) results.commit()
if step % eval_every == 0 or step == steps_total: val_loss = evaluate(valid_data, "validation") improved = val_loss < best_loss log_metric("validation", iteration=step, total_iterations=steps_total, loss=val_loss, best=improved) print(f"step {step}/{steps_total} validation_loss={val_loss:.4f}", flush=True) if improved: best_loss = val_loss best_step = step adapter_dir = root / "best-adapter" model.save_pretrained(adapter_dir, safe_serialization=True) write_status( "training", current_iteration=step, total_iterations=steps_total, best_validation_loss=best_loss, best_iteration=best_step, ) results.commit()
test_loss = evaluate(test_data, "test") adapter_dir = root / "final-adapter" model.save_pretrained(adapter_dir, safe_serialization=True) final = { "status": "complete", "completed_at": datetime.now(timezone.utc).isoformat(), "elapsed_seconds": round(time.time() - started, 2), "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "gpu": "L4", "train_examples": len(train_data), "validation_examples": len(valid_data), "test_examples": len(test_data), "updates_completed": step, "early_stopped": False, "best_iteration": best_step, "best_validation_loss": best_loss, "baseline_validation_loss": baseline_loss, "test_loss": test_loss, "trainable_parameters": trainable, "peak_gpu_memory_gb": round(torch.cuda.max_memory_allocated() / 1e9, 3), "adapter_dir": f"{run_id}/final-adapter", "selection": "final adapter after every training example was processed once", "validation_best_adapter_dir": f"{run_id}/best-adapter", "adapter_strength_note": "Adapter is separate and unmerged. LoRA alpha/r=2.0; API default style_strength is 1.0.", } (root / "result.json").write_text(json.dumps(final, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") write_status("complete", **final) log_metric("test", loss=test_loss, best_iteration=best_step) results.commit() del model, tokenizer, optimizer, scheduler gc.collect() torch.cuda.empty_cache() print(json.dumps(final, ensure_ascii=False), flush=True) return final except BaseException as exc: failure = { "status": "failed", "error_type": type(exc).__name__, "error": str(exc), "elapsed_seconds": round(time.time() - started, 2), } try: write_status("failed", **failure) results.commit() except Exception: pass raise
@app.local_entrypoint()def main(): from datetime import datetime, timezone
run_id = datetime.now(timezone.utc).strftime("run-%Y%m%dT%H%M%SZ") launch_path = HERE / "launch.json" launch_path.write_text(json.dumps({"run_id": run_id, "app_name": APP_NAME, "volume_name": VOLUME_NAME, "launched_at": datetime.now(timezone.utc).isoformat()}, indent=2) + "\n") print("RUN_ID=" + run_id, flush=True) result = train.remote(run_id) print("TRAINING_RESULT=" + json.dumps(result, ensure_ascii=False))12345678910111213141516171819202122232425262728293031323334{ "model_id": "Qwen/Qwen3.5-4B", "model_revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "gpu": "L4", "cpu_cores": 4, "host_memory_gib": 32, "method": "BF16 LoRA SFT", "epochs_target": 1, "optimizer": "AdamW", "learning_rate": 0.0001, "weight_decay": 0.01, "warmup_ratio": 0.03, "batch_size": 1, "gradient_checkpointing": true, "rank": 8, "lora_alpha": 16, "lora_dropout": 0.05, "target_modules": [ "q_proj", "v_proj", "gate_proj", "up_proj", "down_proj" ], "max_sequence_length": 1024, "max_prompt_tokens": 512, "max_answer_tokens": 512, "loss_mask": "prompt tokens ignored; assistant answer and end token trained", "duplicate_answers": "preserved at full frequency", "checkpoint_selection": "final adapter after all training examples; validation-best checkpoint also retained", "trainable_parameters": 9961472, "total_parameters": 4549227008, "dataset_manifest_sha256": "126ffc526c5556e1a2b727296e2ec46e6f5e522e7823c0b7d380863eab68c1a0"}123456789101112131415161718192021{ "status": "complete", "completed_at": "2026-10-07T09:15:04.228105+00:00", "elapsed_seconds": 5588.65, "model_id": "Qwen/Qwen3.5-4B", "model_revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "gpu": "L4", "train_examples": 5204, "validation_examples": 651, "test_examples": 651, "updates_completed": 5204, "early_stopped": false, "best_iteration": 5204, "best_validation_loss": 3.849141866862781, "baseline_validation_loss": 5.611189542769152, "test_loss": 3.8509689247715775, "trainable_parameters": 9961472, "peak_gpu_memory_gb": 11.218, "selection": "final adapter after every training example was processed once", "adapter_strength_note": "Adapter is separate and unmerged. LoRA alpha/r=2.0; API default style_strength is 1.0."}LICENSEAdded+202
README.mdAdded+73
SHA256SUMSAdded+10
adapter_config.jsonAdded+49
adapter_model.safetensorsAdded+3
dataset_summary.jsonAdded+44
prepare_dataset.pyAdded+159
requirements.txtAdded+7
train_modal.pyAdded+418
training_config.jsonAdded+34
training_results.jsonAdded+21