Views
No views yet
If anyone wants to train their own llama-3-8b model for free on any dataset
that has around 1,500 lines of data or less you can now do it easily by using
the code I provided in the model card for my test model in this repo and
google colab. The training for this model uses (Unsloth + Qlora + Galore) to
achieve the ability for training under such low vram. 1%%capture
2import torch
3major_version, minor_version = torch.cuda.get_device_capability()
4# Must install separately since Colab has torch 2.2.1, which breaks packages
5!pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
6
7if major_version >= 8:
8 # Use this for new GPUs like Ampere, Hopper GPUs (RTX 30xx, RTX 40xx, A100, H100, L40)
9 !pip install --no-deps packaging ninja einops flash-attn xformers trl peft accelerate bitsandbytes
10else:
11 # Use this for older GPUs (V100, Tesla T4, RTX 20xx)
12 !pip install --no-deps xformers trl peft accelerate bitsandbytes
13pass!pip install galore_torch1from unsloth import FastLanguageModel
2import torch
3max_seq_length = 8192 # Choose any! We auto support RoPE Scaling internally!
4dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
5load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
6
7# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
8fourbit_models = [
9 "unsloth/mistral-7b-bnb-4bit",
10 "unsloth/mistral-7b-instruct-v0.2-bnb-4bit",
11 "unsloth/llama-2-7b-bnb-4bit",
12 "unsloth/gemma-7b-bnb-4bit",
13 "unsloth/gemma-7b-it-bnb-4bit", # Instruct version of Gemma 7b
14 "unsloth/gemma-2b-bnb-4bit",
15 "unsloth/gemma-2b-it-bnb-4bit", # Instruct version of Gemma 2b
16 "unsloth/llama-3-8b-bnb-4bit", # [NEW] 15 Trillion token Llama-3
17] # More models at https://huggingface.co/unsloth
18
19model, tokenizer = FastLanguageModel.from_pretrained(
20 model_name = "unsloth/llama-3-8b-Instruct",
21 max_seq_length = max_seq_length,
22 dtype = dtype,
23 load_in_4bit = load_in_4bit,
24 # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
25)1model = FastLanguageModel.get_peft_model(
2 model,
3 r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
4 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
5 "gate_proj", "up_proj", "down_proj",],
6 lora_alpha = 16,
7 lora_dropout = 0, # Supports any, but = 0 is optimized
8 bias = "none", # Supports any, but = "none" is optimized
9 # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
10 use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
11 random_state = 3407,
12 use_rslora = False, # We support rank stabilized LoRA
13 loftq_config = None, # And LoftQ
14)1
2alpaca_prompt = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
3
4Below is an instruction that describes a task, Write a response that appropriately completes the request.<|eot_id|><|start_header_id|>user<|end_header_id|>
5
6{}<|eot_id|><|start_header_id|>assistant<|end_header_id|>{}"""
7
8EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
9def formatting_prompts_func(examples):
10 inputs = examples["human"]
11 outputs = examples["assistant"]
12 texts = []
13 for input, output in zip(inputs, outputs):
14 # Must add EOS_TOKEN, otherwise your generation will go on forever!
15 text = alpaca_prompt.format(input, output) + EOS_TOKEN
16 texts.append(text)
17 return { "text" : texts, }
18pass
19
20from datasets import load_dataset
21dataset = load_dataset("Replete-AI/code-test-dataset", split = "train")
22dataset = dataset.map(formatting_prompts_func, batched = True,)1from trl import SFTTrainer
2from transformers import TrainingArguments
3from galore_torch import GaLoreAdamW8bit
4import torch.nn as nn
5galore_params = []
6target_modules_list = ["attn", "mlp"]
7for module_name, module in model.named_modules():
8 if not isinstance(module, nn.Linear):
9 continue
10
11 if not any(target_key in module_name for target_key in target_modules_list):
12 continue
13
14 print('mod ', module_name)
15 galore_params.append(module.weight)
16id_galore_params = [id(p) for p in galore_params]
17regular_params = [p for p in model.parameters() if id(p) not in id_galore_params]
18
19
20param_groups = [{'params': regular_params},
21 {'params': galore_params, 'rank': 64, 'update_proj_gap': 200, 'scale': 0.25, 'proj_type': 'std'}]
22
23optimizer = GaLoreAdamW8bit(param_groups, lr=2e-5)
24
25trainer = SFTTrainer(
26 model = model,
27 tokenizer = tokenizer,
28 train_dataset = dataset,
29 optimizers=(optimizer, None),
30 dataset_text_field = "text",
31 max_seq_length = max_seq_length,
32 dataset_num_proc = 2,
33 packing = True, # Can make training 5x faster for short sequences.
34 args = TrainingArguments(
35 per_device_train_batch_size = 1,
36 gradient_accumulation_steps = 4,
37 warmup_steps = 5,
38 learning_rate = 2e-4,
39 fp16 = not torch.cuda.is_bf16_supported(),
40 bf16 = torch.cuda.is_bf16_supported(),
41 logging_steps = 1,
42 weight_decay = 0.01,
43 lr_scheduler_type = "linear",
44 seed = 3407,
45 output_dir = "outputs",
46 ),
47)1trainer_stats = trainer.train()
2model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
3model.push_to_hub_merged("rombodawg/test_dataset_Codellama-3-8B", tokenizer, save_method = "merged_16bit", token = "")