wheattoast11 commited on
Commit
20fa6f2
·
verified ·
1 Parent(s): 9e59c32

Upload train_glm_qlora_v11.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_glm_qlora_v11.py +152 -0
train_glm_qlora_v11.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "trl>=0.12.0",
5
+ # "peft>=0.7.0",
6
+ # "transformers @ git+https://github.com/huggingface/transformers.git",
7
+ # "accelerate @ git+https://github.com/huggingface/accelerate.git",
8
+ # "bitsandbytes>=0.45.0",
9
+ # "trackio",
10
+ # "datasets",
11
+ # ]
12
+ # ///
13
+
14
+ """
15
+ Agent Zero SFT: zai-org/GLM-4.7-Flash (30B MoE)
16
+ QLoRA (4-bit) on l40sx1 (48GB) with monkey-patch for CPU offload compat.
17
+ Patches both Params4bit.__new__ and quant_state.as_dict for meta tensors.
18
+ """
19
+
20
+ import os
21
+ import torch
22
+
23
+ # === Monkey-patches for bitsandbytes + accelerate CPU offload compat ===
24
+
25
+ import bitsandbytes as bnb
26
+ from bitsandbytes import functional as bnb_func
27
+
28
+ # Patch 1: Params4bit.__new__ to accept _is_hf_initialized kwarg
29
+ _orig_params4bit_new = bnb.nn.Params4bit.__new__
30
+ def _patched_params4bit_new(cls, *args, **kwargs):
31
+ kwargs.pop('_is_hf_initialized', None)
32
+ return _orig_params4bit_new(cls, *args, **kwargs)
33
+ bnb.nn.Params4bit.__new__ = _patched_params4bit_new
34
+
35
+ # Patch 2: QuantState.as_dict to handle meta tensors (offset.item() fails on meta)
36
+ _orig_as_dict = bnb_func.QuantState.as_dict
37
+ def _patched_as_dict(self, packed=False):
38
+ try:
39
+ return _orig_as_dict(self, packed=packed)
40
+ except RuntimeError as e:
41
+ if "meta tensors" in str(e):
42
+ # Return a minimal dict when on meta device
43
+ result = {
44
+ "quant_type": self.quant_type,
45
+ "blocksize": self.blocksize,
46
+ }
47
+ if hasattr(self, 'shape'):
48
+ result["shape"] = self.shape
49
+ return result
50
+ raise
51
+ bnb_func.QuantState.as_dict = _patched_as_dict
52
+
53
+ print("Patched bitsandbytes for CPU offload compat")
54
+
55
+ # === Main training script ===
56
+
57
+ import trackio
58
+ from huggingface_hub import login
59
+ login(token=os.environ["HF_TOKEN"])
60
+
61
+ from datasets import load_dataset
62
+ from peft import LoraConfig
63
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
64
+ from trl import SFTTrainer, SFTConfig
65
+
66
+ print("Loading dataset...")
67
+ train_ds = load_dataset("wheattoast11/agent-zero-sft-v1", data_files="data/train.jsonl", split="train")
68
+ val_ds = load_dataset("wheattoast11/agent-zero-sft-v1", data_files="data/validation.jsonl", split="train")
69
+ print(f"Train: {len(train_ds)}, Val: {len(val_ds)}")
70
+
71
+ bnb_config = BitsAndBytesConfig(
72
+ load_in_4bit=True,
73
+ bnb_4bit_quant_type="nf4",
74
+ bnb_4bit_compute_dtype=torch.bfloat16,
75
+ bnb_4bit_use_double_quant=True,
76
+ llm_int8_enable_fp32_cpu_offload=True,
77
+ )
78
+
79
+ offload_dir = "/tmp/offload"
80
+ os.makedirs(offload_dir, exist_ok=True)
81
+
82
+ print("Loading model in 4-bit with CPU offload on l40sx1...")
83
+ model = AutoModelForCausalLM.from_pretrained(
84
+ "zai-org/GLM-4.7-Flash",
85
+ quantization_config=bnb_config,
86
+ trust_remote_code=True,
87
+ device_map="auto",
88
+ max_memory={0: "44GiB", "cpu": "60GiB"},
89
+ offload_folder=offload_dir,
90
+ torch_dtype=torch.bfloat16,
91
+ )
92
+ tokenizer = AutoTokenizer.from_pretrained("zai-org/GLM-4.7-Flash", trust_remote_code=True)
93
+ print("Model loaded.")
94
+
95
+ if hasattr(model, 'hf_device_map'):
96
+ devices = {}
97
+ for v in model.hf_device_map.values():
98
+ devices[str(v)] = devices.get(str(v), 0) + 1
99
+ print(f"Device distribution: {devices}")
100
+
101
+ import subprocess
102
+ result = subprocess.run(['nvidia-smi'], capture_output=True, text=True)
103
+ print(result.stdout)
104
+
105
+ config = SFTConfig(
106
+ output_dir="agent-zero-glm-4.7-v1",
107
+ push_to_hub=True,
108
+ hub_model_id="wheattoast11/agent-zero-glm-4.7-v1",
109
+ hub_strategy="every_save",
110
+ hub_private_repo=True,
111
+ num_train_epochs=2,
112
+ per_device_train_batch_size=1,
113
+ gradient_accumulation_steps=16,
114
+ learning_rate=1e-4,
115
+ bf16=True,
116
+ gradient_checkpointing=True,
117
+ logging_steps=10,
118
+ save_strategy="steps",
119
+ save_steps=50,
120
+ save_total_limit=2,
121
+ eval_strategy="steps",
122
+ eval_steps=50,
123
+ warmup_ratio=0.1,
124
+ lr_scheduler_type="cosine",
125
+ report_to="trackio",
126
+ project="agent-zero-finetune",
127
+ run_name="glm-4.7-flash-qlora-v1",
128
+ )
129
+
130
+ peft_config = LoraConfig(
131
+ r=16, lora_alpha=32, lora_dropout=0.05,
132
+ bias="none", task_type="CAUSAL_LM",
133
+ target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
134
+ )
135
+
136
+ print("Initializing trainer...")
137
+ trainer = SFTTrainer(
138
+ model=model,
139
+ tokenizer=tokenizer,
140
+ train_dataset=train_ds,
141
+ eval_dataset=val_ds,
142
+ args=config,
143
+ peft_config=peft_config,
144
+ )
145
+
146
+ print("Starting training...")
147
+ trainer.train()
148
+
149
+ print("Pushing to Hub...")
150
+ trainer.push_to_hub()
151
+ trackio.finish()
152
+ print("Done!")