AvaSiG commited on
Commit
83d3ddc
·
verified ·
1 Parent(s): 742807e

Upload argos_train_all_datasets.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. argos_train_all_datasets.ipynb +283 -0
argos_train_all_datasets.ipynb ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# ARGOS LoRA Training — AvaSiG/111 Collection\n",
8
+ "Запускать в Colab с GPU (T4/A100/V100)"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "metadata": {},
15
+ "outputs": [],
16
+ "source": [
17
+ "# 1. Проверка GPU\n",
18
+ "!nvidia-smi\n",
19
+ "import torch\n",
20
+ "print(f'CUDA: {torch.cuda.is_available()}, устройство: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"нет\"}')\n",
21
+ "print(f'VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB')"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "# 2. Установка зависимостей\n",
31
+ "!pip install -q transformers==4.47.0 peft==0.13.2 trl==0.12.2 bitsandbytes==0.44.1 datasets accelerate huggingface_hub"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": null,
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": "import os\n\n# HF токен: добавить в Colab через левую панель → секреты → ключ \"HF_TOKEN\"\ntry:\n from google.colab import userdata\n HF_TOKEN = userdata.get('HF_TOKEN')\nexcept Exception:\n HF_TOKEN = os.environ.get('HF_TOKEN', '')\n\nassert HF_TOKEN, \"Добавьте токен HF_TOKEN в Colab Secrets!\"\n\nos.environ['HF_TOKEN'] = HF_TOKEN\nos.environ['HUGGINGFACE_HUB_TOKEN'] = HF_TOKEN\nos.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'\n\nfrom huggingface_hub import login\nlogin(token=HF_TOKEN, add_to_git_credential=False)\nprint('HF авторизован')"
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "# 3. Загрузка и объединение всех датасетов коллекции AvaSiG/111\n",
48
+ "import torch\n",
49
+ "from datasets import load_dataset, concatenate_datasets, Dataset\n",
50
+ "\n",
51
+ "# Все датасеты из коллекции (без codeparrot — 71GB не помещается, берём 100k сэмпл)\n",
52
+ "DATASETS = [\n",
53
+ " # (repo_id, max_rows или None=всё)\n",
54
+ " ('AvaSiG/ru-thinking-reasoning-r1-v2-deduped-bucket', None),\n",
55
+ " ('AvaSiG/ru-thinking-reasoning-r1-deduped-bucket', None),\n",
56
+ " ('AvaSiG/ru-tasks-conversation-deduped-bucket', None),\n",
57
+ " ('AvaSiG/ru-instruct-conversation-v3.1-small-bucket', None),\n",
58
+ " ('AvaSiG/ru-big-russian-dataset-bucket', 200_000), # 4GB → сэмпл\n",
59
+ " ('AvaSiG/codeparrot-bucket', 100_000), # 71GB → сэмпл\n",
60
+ "]\n",
61
+ "\n",
62
+ "SEED = 42\n",
63
+ "\n",
64
+ "def extract_text(row, col_names):\n",
65
+ " \"\"\"Авто-определение текста по доступным колонкам.\"\"\"\n",
66
+ " # Готовый text\n",
67
+ " if 'text' in col_names and row.get('text'):\n",
68
+ " return row['text']\n",
69
+ " # content (big russian dataset)\n",
70
+ " if 'content' in col_names and row.get('content'):\n",
71
+ " return row['content']\n",
72
+ " # chat-формат messages\n",
73
+ " if 'messages' in col_names and row.get('messages'):\n",
74
+ " msgs = row['messages']\n",
75
+ " if isinstance(msgs, str):\n",
76
+ " import json\n",
77
+ " try: msgs = json.loads(msgs)\n",
78
+ " except: return msgs\n",
79
+ " txt = ''\n",
80
+ " for m in msgs:\n",
81
+ " r = m.get('role', '')\n",
82
+ " c = m.get('content', '')\n",
83
+ " if r == 'system': txt += f'<|im_start|>system\\n{c}<|im_end|>\\n'\n",
84
+ " elif r == 'user': txt += f'<|im_start|>user\\n{c}<|im_end|>\\n'\n",
85
+ " elif r == 'assistant': txt += f'<|im_start|>assistant\\n{c}<|im_end|>\\n'\n",
86
+ " return txt\n",
87
+ " # conversation колонка\n",
88
+ " if 'conversation' in col_names and row.get('conversation'):\n",
89
+ " msgs = row['conversation']\n",
90
+ " if isinstance(msgs, str):\n",
91
+ " import json\n",
92
+ " try: msgs = json.loads(msgs)\n",
93
+ " except: return msgs\n",
94
+ " txt = ''\n",
95
+ " for m in msgs:\n",
96
+ " r = m.get('role', '') or m.get('from', '')\n",
97
+ " c = m.get('content', '') or m.get('value', '')\n",
98
+ " if r in ('system', 'gpt'): txt += f'<|im_start|>system\\n{c}<|im_end|>\\n'\n",
99
+ " elif r in ('user', 'human'): txt += f'<|im_start|>user\\n{c}<|im_end|>\\n'\n",
100
+ " elif r in ('assistant', 'gpt'): txt += f'<|im_start|>assistant\\n{c}<|im_end|>\\n'\n",
101
+ " return txt\n",
102
+ " # instruction + output\n",
103
+ " if 'instruction' in col_names:\n",
104
+ " inst = row.get('instruction', '')\n",
105
+ " inp = row.get('input', '')\n",
106
+ " out = row.get('output', '')\n",
107
+ " prompt = f'{inst}\\n{inp}'.strip() if inp else inst\n",
108
+ " return f'<|im_start|>user\\n{prompt}<|im_end|>\\n<|im_start|>assistant\\n{out}<|im_end|>\\n'\n",
109
+ " # code колонка (codeparrot)\n",
110
+ " if 'code' in col_names and row.get('code'):\n",
111
+ " return row['code']\n",
112
+ " return ''\n",
113
+ "\n",
114
+ "all_datasets = []\n",
115
+ "\n",
116
+ "for repo_id, max_rows in DATASETS:\n",
117
+ " print(f'\\nЗагружаю {repo_id}...')\n",
118
+ " try:\n",
119
+ " ds = load_dataset(repo_id, split='train', token=HF_TOKEN)\n",
120
+ " print(f' строк: {len(ds)}, колонки: {ds.column_names}')\n",
121
+ " if max_rows and len(ds) > max_rows:\n",
122
+ " ds = ds.shuffle(seed=SEED).select(range(max_rows))\n",
123
+ " print(f' → сэмпл: {len(ds)}')\n",
124
+ " col_names = ds.column_names\n",
125
+ " ds = ds.map(lambda r: {'text': extract_text(r, col_names)}, remove_columns=col_names)\n",
126
+ " ds = ds.filter(lambda x: len(x['text']) > 100)\n",
127
+ " print(f' после фильтра: {len(ds)}')\n",
128
+ " all_datasets.append(ds)\n",
129
+ " except Exception as e:\n",
130
+ " print(f' ОШИБКА: {e}')\n",
131
+ "\n",
132
+ "combined = concatenate_datasets(all_datasets).shuffle(seed=SEED)\n",
133
+ "split = combined.train_test_split(test_size=0.02, seed=SEED)\n",
134
+ "train_ds = split['train']\n",
135
+ "val_ds = split['test']\n",
136
+ "print(f'\\nИтого: train={len(train_ds)}, val={len(val_ds)}')\n",
137
+ "print('Пример:', train_ds[0]['text'][:300])"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "execution_count": null,
143
+ "metadata": {},
144
+ "outputs": [],
145
+ "source": [
146
+ "# 4. Загрузка модели Qwen2.5-7B-Instruct с 4-bit quantization\n",
147
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
148
+ "from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n",
149
+ "import torch.nn as nn\n",
150
+ "\n",
151
+ "if not hasattr(nn.Module, 'set_submodule'):\n",
152
+ " def _set_submodule(self, target, module):\n",
153
+ " parts = target.split('.')\n",
154
+ " parent = self\n",
155
+ " for part in parts[:-1]:\n",
156
+ " parent = getattr(parent, part)\n",
157
+ " setattr(parent, parts[-1], module)\n",
158
+ " nn.Module.set_submodule = _set_submodule\n",
159
+ "\n",
160
+ "MODEL = 'Qwen/Qwen2.5-7B-Instruct'\n",
161
+ "OUTPUT = '/content/argos-qwen7b-lora-v3'\n",
162
+ "\n",
163
+ "tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True, token=HF_TOKEN)\n",
164
+ "if tokenizer.pad_token is None:\n",
165
+ " tokenizer.pad_token = tokenizer.eos_token\n",
166
+ "\n",
167
+ "bnb = BitsAndBytesConfig(\n",
168
+ " load_in_4bit=True,\n",
169
+ " bnb_4bit_quant_type='nf4',\n",
170
+ " bnb_4bit_compute_dtype=torch.bfloat16,\n",
171
+ " bnb_4bit_use_double_quant=True,\n",
172
+ ")\n",
173
+ "model = AutoModelForCausalLM.from_pretrained(\n",
174
+ " MODEL,\n",
175
+ " quantization_config=bnb,\n",
176
+ " device_map={'': 0},\n",
177
+ " trust_remote_code=True,\n",
178
+ " token=HF_TOKEN,\n",
179
+ ")\n",
180
+ "model = prepare_model_for_kbit_training(model)\n",
181
+ "\n",
182
+ "lora = LoraConfig(\n",
183
+ " r=16,\n",
184
+ " lora_alpha=32,\n",
185
+ " target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],\n",
186
+ " lora_dropout=0.05,\n",
187
+ " bias='none',\n",
188
+ " task_type='CAUSAL_LM',\n",
189
+ ")\n",
190
+ "model = get_peft_model(model, lora)\n",
191
+ "model.print_trainable_parameters()\n",
192
+ "print('Модель готова')"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": [
201
+ "# 5. Обучение\n",
202
+ "from trl import SFTTrainer, SFTConfig\n",
203
+ "\n",
204
+ "args = SFTConfig(\n",
205
+ " output_dir=OUTPUT,\n",
206
+ " num_train_epochs=3,\n",
207
+ " per_device_train_batch_size=1,\n",
208
+ " per_device_eval_batch_size=1,\n",
209
+ " gradient_accumulation_steps=8,\n",
210
+ " learning_rate=2e-4,\n",
211
+ " fp16=False,\n",
212
+ " bf16=True,\n",
213
+ " gradient_checkpointing=True,\n",
214
+ " logging_steps=20,\n",
215
+ " save_strategy='steps',\n",
216
+ " save_steps=500,\n",
217
+ " eval_strategy='steps',\n",
218
+ " eval_steps=500,\n",
219
+ " load_best_model_at_end=False,\n",
220
+ " save_total_limit=2,\n",
221
+ " remove_unused_columns=False,\n",
222
+ " dataloader_num_workers=2,\n",
223
+ " lr_scheduler_type='cosine',\n",
224
+ " warmup_ratio=0.05,\n",
225
+ " dataset_text_field='text',\n",
226
+ " max_length=1024,\n",
227
+ " pad_to_multiple_of=8,\n",
228
+ " push_to_hub=False,\n",
229
+ " weight_decay=0.01,\n",
230
+ " report_to='none',\n",
231
+ ")\n",
232
+ "\n",
233
+ "trainer = SFTTrainer(\n",
234
+ " model=model,\n",
235
+ " processing_class=tokenizer,\n",
236
+ " train_dataset=train_ds,\n",
237
+ " eval_dataset=val_ds,\n",
238
+ " args=args,\n",
239
+ ")\n",
240
+ "\n",
241
+ "print(f'Шагов всего: {len(trainer.get_train_dataloader()) * args.num_train_epochs}')\n",
242
+ "trainer.train()\n",
243
+ "print('Обучение завершено!')"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "execution_count": null,
249
+ "metadata": {},
250
+ "outputs": [],
251
+ "source": [
252
+ "# 6. Сохранение и загрузка на HF Hub\n",
253
+ "LORA_OUT = OUTPUT + '/final_lora'\n",
254
+ "model.save_pretrained(LORA_OUT)\n",
255
+ "tokenizer.save_pretrained(LORA_OUT)\n",
256
+ "print(f'Сохранено в {LORA_OUT}')\n",
257
+ "\n",
258
+ "from huggingface_hub import HfApi\n",
259
+ "api = HfApi(token=HF_TOKEN)\n",
260
+ "api.create_repo('AvaSiG/argos-qwen2.5-7b-v3', exist_ok=True, private=False)\n",
261
+ "api.upload_folder(folder_path=LORA_OUT, repo_id='AvaSiG/argos-qwen2.5-7b-v3')\n",
262
+ "print('Готово! Загружено в AvaSiG/argos-qwen2.5-7b-v3')"
263
+ ]
264
+ }
265
+ ],
266
+ "metadata": {
267
+ "accelerator": "GPU",
268
+ "colab": {
269
+ "gpuType": "T4",
270
+ "name": "argos_train_all_datasets.ipynb",
271
+ "provenance": []
272
+ },
273
+ "kernelspec": {
274
+ "display_name": "Python 3",
275
+ "name": "python3"
276
+ },
277
+ "language_info": {
278
+ "name": "python"
279
+ }
280
+ },
281
+ "nbformat": 4,
282
+ "nbformat_minor": 0
283
+ }