Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • dbis-public/test-gpu-container
  • martin.sboron/test-gpu-container-ms
  • ajntx/faith-fate-gpu-container
  • akzab/test-gpu-container-mcc
  • ambcj/gpu-training
  • apcne/galore-replication
6 results
Select Git revision
Show changes
Commits on Source (95)
Showing with 922 additions and 87 deletions
__pycache__
test.py
output.txt
output.csv
models/
.idea/
venv/
\ No newline at end of file
......@@ -24,7 +24,7 @@ docker-build:
fi
# Run this job in a branch where a Dockerfile exists
rules:
- if: $CI_COMMIT_BRANCH
- if: $CI_COMMIT_BRANCH == "main"
exists:
- Dockerfile
FROM nvidia/cuda:12.3.0-devel-ubuntu20.04
RUN apt-get update && apt-get install -y \
python3 \
python3-pip \
&& rm -rf /var/lib/apt/lists/*
RUN pip3 install --upgrade pip
COPY requirements.txt /workspace/requirements.txt
RUN pip3 install -r /workspace/requirements.txt
WORKDIR /workspace
# test-gpu-container
# Training Script Documentation
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.informatik.uni-halle.de/dbis-public/test-gpu-container.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.informatik.uni-halle.de/dbis-public/test-gpu-container/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Overview
This script is designed to facilitate model training with various configurations. Users can specify multiple parameters, including the training mode, optimizer, model type, and other training settings.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
```bash
python train.py --mode <mode> --optimizer <optimizer> --model <model> [other options]
```
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## Input Parameters
### Required Parameters
| Parameter | Type | Choices | Description |
|-------------|--------|------------------------------------------|------------------------------------|
| `--mode` | string | `pretraining`, `finetuning` | Specifies the training mode. |
| `--optimizer` | string | `lora`, `galore`, `galore8bit`, `lora+galore8bit`, `baseline` | Selects the optimizer type. |
| `--model` | string | `llama_60m`, `llama_1b`, `llama_7b`, `roberta`, `gpt2` | Defines the model to train. |
### Optional Parameters
| Parameter | Type | Default | Choices | Description |
|-----------------|------|----------|---------|-------------|
| `--batch_size` | int | `16` | N/A | Number of samples per batch. |
| `--num_epochs` | int | `30` | N/A | Number of training epochs. |
| `--max_length` | int | `512` | N/A | Maximum token length per input. |
| `--num_training_tokens` | int | `1e9` | N/A | Number of training tokens (only for pretraining). |
| `--shuffle` | string | `true` | `true`, `false` | Whether to shuffle training data (not applicable in streaming mode). |
| `--dtype` | string | `fp16` | `bf16`, `fp16` | Data type for training (currently only `bf16` is working). |
| `--lr` | float | `4e-4` | N/A | Learning rate for optimizer. |
| `--weight_decay` | float | `0.01` | N/A | Weight decay for optimizer. |
| `--tmax` | int | `30` | N/A | Tmax for scheduler. |
| `--lora_config` | string | `config/lora_config.json` | N/A | Path to the LoRa configuration file. |
| `--galore_config` | string | `config/galore_config.json` | N/A | Path to the GaLore configuration file. |
| `--test` | string | `false` | `true`, `false` | Whether to enable test mode. Takes only 1000 tokens of dataset for pretraining and accelerator without bf16 (useful only for A100 GPUs). |
## Example Command
```bash
python train.py --mode pretraining --optimizer lora --model llama_1b --batch_size 32 --num_epochs 20 --shuffle false --lr 3e-4
```
## License
For open source projects, say how it is licensed.
This command runs the script in pretraining mode using the LoRa optimizer on the `llama_1b` model with a batch size of 32, 20 epochs, no data shuffling, and a learning rate of `3e-4`.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
import argparse
parser = argparse.ArgumentParser(description="Run training")
parser.add_argument("--mode", type=str, choices=["pretraining", "finetuning"], required=True, help="Training mode to use")
parser.add_argument("--model", type=str, choices=["llama_60m", "llama_350m" , "llama_1b", "llama_3b" , "llama_7b", "roberta", "gpt2"], required=True, help="Model to use")
parser.add_argument("--dataset", type=str, choices=["c4", "glue_mnli", "glue_sst-2", "glue_mrpc", "glue_cola", "glue_qnli", "glue_qqp", "glue_rte", "glue_sts-b"], required=True, help="Model to use")
parser.add_argument("--optimizer", type=str, choices=["galore", "galore8bit", "adamw"], required=True, help="Optimizer type to use")
parser.add_argument("--peft", type=str, choices=["lora", "none"], default=None, help="Parameter Efficient Fine-Tuning method")
parser.add_argument("--weight_decay", type=float, default=0, help="Weight decay for optimizer")
parser.add_argument("--rank", type=int, default=128, help="Rank of the sub-space for LoRA and GaLore")
parser.add_argument("--galore_alpha", type=float, default=1.0, help="Scaling factor for optimizer updates")
parser.add_argument("--galore_T", type=int, default=200, help="Sub-space change frequency")
parser.add_argument("--lora_alpha", type=float, default=1.0, help="Scaling factor for optimizer updates")
parser.add_argument("--lora_dropout", type=float, default=0.1, help="Dropout rate for LoRA")
parser.add_argument("--lr_scheduler", type=str, choices=["constant", "linear", "cosine"], default="constant")
parser.add_argument("--lr", type=float, default=4e-4, help="Learning rate for optimizer")
parser.add_argument("--lr_min", type=float, default=0, help="Minimum learning rate for annealing")
parser.add_argument("--warm_up_fraction", type=float, default=0, help="Fraction of training steps to use maximum learning rate as a warm-up")
parser.add_argument("--batch_size", type=int, default=16, help="Batch size")
parser.add_argument("--num_epochs", type=int, default=1, help="Number of epochs")
parser.add_argument("--max_length", type=int, default=512, help="Max length of input tokens")
parser.add_argument("--num_training_steps", type=int, default=None, help="Number of training steps/batches")
parser.add_argument("--num_eval_steps", type=int, default=None, help="Number of evaluation steps/batches")
parser.add_argument("--eval_every", type=int, default=10, help="Evaluate the model (and print results) every X training steps")
parser.add_argument("--shuffle", type=str, choices=["true", "false"], default="false", help="Shuffle data (doesn't work in streaming mode)")
parser.add_argument("--dtype", type=str, choices=["bf16", "fp16"], default="fp16", help="Data type to use") # TODO for now just bf16 working
parser.add_argument("--gradient_checkpointing", type=str, choices=["true", "false"], default="false", help="Enable gradient checkpointing.")
parser.add_argument("--lomo", type=str, choices=["true", "false"], default="false", help="Enable LOMO (per-layer weight updates).")
parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Number of steps to accumulate gradients before updating the model.")
# parser.add_argument("--tmax", type=int, default=30, help="Tmax for scheduler")
parser.add_argument("--lora_config", type=str, default=None, help="Path to LoRa config file")
parser.add_argument("--galore_config", type=str, default=None, help="Path to GaLore config file")
parser.add_argument("--test", type=str, choices=["true", "false"], default="false", help="Test mode")
args = parser.parse_args()
# Copyright Notice
The LLaMa config files are the ones used in the original [GaLore project](https://github.com/jiaweizzhao/GaLore).\
Since we want to replicate the results, we're using exactly the same settings for the LLaMa models in our experiences.
\ No newline at end of file
{
"rank": 128,
"update_proj_gap": 200,
"scale": 0.25,
"proj_type": "std"
}
{
"architectures": [
"LLaMAForCausalLM"
],
"bos_token_id": 0,
"eos_token_id": 1,
"hidden_act": "silu",
"hidden_size": 2048,
"intermediate_size": 5461,
"initializer_range": 0.02,
"max_sequence_length": 1024,
"model_type": "llama",
"num_attention_heads": 32,
"num_hidden_layers": 24,
"pad_token_id": -1,
"rms_norm_eps": 1e-06,
"transformers_version": "4.28.1",
"use_cache": true,
"vocab_size": 32000
}
\ No newline at end of file
{
"architectures": [
"LLaMAForCausalLM"
],
"bos_token_id": 0,
"eos_token_id": 1,
"hidden_act": "silu",
"hidden_size": 1024,
"intermediate_size": 2736,
"initializer_range": 0.02,
"max_sequence_length": 1024,
"model_type": "llama",
"num_attention_heads": 16,
"num_hidden_layers": 24,
"pad_token_id": -1,
"rms_norm_eps": 1e-06,
"transformers_version": "4.28.1",
"use_cache": true,
"vocab_size": 32000
}
\ No newline at end of file
{
"architectures": [
"LLaMAForCausalLM"
],
"bos_token_id": 0,
"eos_token_id": 1,
"hidden_act": "silu",
"hidden_size": 2560,
"intermediate_size": 6848,
"initializer_range": 0.02,
"max_sequence_length": 1024,
"model_type": "llama",
"num_attention_heads": 32,
"num_hidden_layers": 32,
"pad_token_id": -1,
"rms_norm_eps": 1e-06,
"transformers_version": "4.28.1",
"use_cache": true,
"vocab_size": 32000
}
\ No newline at end of file
{
"architectures": [
"LLaMAForCausalLM"
],
"bos_token_id": 0,
"eos_token_id": 1,
"hidden_act": "silu",
"hidden_size": 512,
"intermediate_size": 1376,
"initializer_range": 0.02,
"max_sequence_length": 1024,
"model_type": "llama",
"num_attention_heads": 8,
"num_hidden_layers": 8,
"pad_token_id": -1,
"rms_norm_eps": 1e-06,
"transformers_version": "4.28.1",
"use_cache": true,
"vocab_size": 32000
}
\ No newline at end of file
{
"architectures": [
"LLaMAForCausalLM"
],
"bos_token_id": 0,
"eos_token_id": 1,
"hidden_act": "silu",
"hidden_size": 4096,
"intermediate_size": 11008,
"initializer_range": 0.02,
"max_sequence_length": 2048,
"model_type": "llama",
"num_attention_heads": 32,
"num_hidden_layers": 32,
"pad_token_id": -1,
"rms_norm_eps": 1e-06,
"transformers_version": "4.28.1",
"use_cache": true,
"vocab_size": 32000
}
\ No newline at end of file
{
"r": 8,
"lora_alpha": 8,
"lora_dropout": 0.1,
"target_modules_finetuning": ["query", "value"],
"target_modules_pretraining": ["q_proj", "v_proj"]
}
import torch
from datasets import load_dataset
from torch.utils.data import DataLoader
arg_map = {
"glue_mnli": ("glue", "mnli"),
"glue_sst-2": ("glue", "sst2"),
"glue_mrpc": ("glue", "mrpc"),
"glue_cola": ("glue", "cola"),
"glue_qnli": ("glue", "qnli"),
"glue_qqp": ("glue", "qqp"),
"glue_rte": ("glue", "rte"),
"glue_sts-b": ("glue", "stsb"),
"glue_wnli": ("glue", "wnli")
}
def get_dataloader(args, tokenizer):
train_dataset, eval_dataset = load_data(args, tokenizer)
shuffle = True if args.shuffle == "true" else False
train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=shuffle)
eval_dataloader = DataLoader(eval_dataset, batch_size=args.batch_size)
return train_dataloader, eval_dataloader
def load_data(args, tokenizer):
if args.mode == "pretraining":
return load_data_pretrain(args, tokenizer)
elif args.mode == "finetuning":
return load_data_finetune(args, tokenizer)
else:
raise ValueError("Invalid mode. Choose 'pretraining' or 'finetuning'")
def load_data_pretrain(args, tokenizer):
def prepare_dataset(dataset):
def tokenize_function_pretrain(batch):
encoding = tokenizer(batch["text"], truncation=True, padding="max_length", max_length=args.max_length)
return {
"input_ids": torch.tensor(encoding["input_ids"]).clone().detach().to(torch.long),
"attention_mask": torch.tensor(encoding["attention_mask"]).clone().detach().to(torch.long),
"labels": torch.tensor(encoding["input_ids"]).clone().detach().to(torch.long).masked_fill(
torch.tensor(encoding["attention_mask"]).clone().detach() == 0, -100)
}
dataset = dataset.map(tokenize_function_pretrain, batched=True, remove_columns=["text", "timestamp", "url"])
dataset.with_format("torch")
return dataset
train_dataset = load_dataset("allenai/c4", "en", split="train", streaming=True)
# TODO Does it make a difference in memory to define this after or before training?
eval_dataset = load_dataset("allenai/c4", "en", split="validation", streaming=True)
train_dataset = prepare_dataset(train_dataset)
eval_dataset = prepare_dataset(eval_dataset)
return train_dataset, eval_dataset
def load_data_finetune(args, tokenizer):
task_to_keys = {
"glue_cola": ("sentence", None),
"glue_mnli": ("premise", "hypothesis"),
"glue_mrpc": ("sentence1", "sentence2"),
"glue_qnli": ("question", "sentence"),
"glue_qqp": ("question1", "question2"),
"glue_rte": ("sentence1", "sentence2"),
"glue_sst-2": ("sentence", None),
"glue_sts-b": ("sentence1", "sentence2"),
"glue_wnli": ("sentence1", "sentence2"),
}
if args.dataset not in arg_map:
raise ValueError(f"Data set '{args.dataset}' not supported for mode 'finetuning'!")
dataset = load_dataset(*arg_map[args.dataset])
# Extract useful text
sentence1_key, sentence2_key = task_to_keys[args.dataset]
def tokenize_function_finetune(batch):
texts = (
(batch[sentence1_key],) if sentence2_key is None else (batch[sentence1_key], batch[sentence2_key])
)
result = tokenizer(*texts, truncation=True, padding="max_length", max_length=args.max_length)
result["labels"] = batch["label"]
return result
dataset = dataset.map(
tokenize_function_finetune,
batched=True,
remove_columns=dataset["train"].column_names,
desc="Running tokenizer on dataset",
)
dataset.set_format(type="torch")
eval_dataset = dataset["validation_matched" if args.dataset == "glue_mnli" else "validation"]
train_dataset = dataset["train"]
return train_dataset, eval_dataset
from torch.optim.lr_scheduler import (
CosineAnnealingLR, LinearLR, ConstantLR, SequentialLR
)
def get_scheduler(
optimizer,
scheduler_type: str,
warm_up_fraction: float,
num_steps: int,
max_lr: float,
min_lr: float = 0.0,
):
warm_up_steps = int(warm_up_fraction * num_steps)
annealing_steps = num_steps - warm_up_steps
# warm_up_scheduler = ConstantLR(optimizer, 1.0, warm_up_steps)
if warm_up_steps > 0:
warm_up_scheduler = LinearLR(optimizer, start_factor=1e-8, end_factor=1.0, total_iters=warm_up_steps) # start factor needs to be greater than 0.0 so we use a small number
if scheduler_type == "constant":
annealing_scheduler = ConstantLR(optimizer, 1.0, annealing_steps)
elif scheduler_type == "linear":
annealing_scheduler = LinearLR(optimizer, 1.0, min_lr / max_lr, annealing_steps)
elif scheduler_type == "cosine":
annealing_scheduler = CosineAnnealingLR(optimizer, annealing_steps, min_lr)
else:
raise ValueError(f"Scheduler option '{scheduler_type}' unknown. Use --help to get all possible options.")
if warm_up_steps == 0:
return annealing_scheduler
return SequentialLR(optimizer, [warm_up_scheduler, annealing_scheduler], [warm_up_steps],)
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer
import torch
from load_data import arg_map
def get_model(args):
""" Creates model for Pretraining or Fine-Tuning """
if args.mode == "pretraining":
model_config = AutoConfig.from_pretrained(f"config/{args.model}.json")
if args.dtype == "bf16":
model = AutoModelForCausalLM.from_config(model_config, torch_dtype=torch.bfloat16)
else:
model = AutoModelForCausalLM.from_config(model_config)
# T5 tokenizer like in the galore project
tokenizer = AutoTokenizer.from_pretrained("t5-base")
if tokenizer.pad_token_id is None:
tokenizer.pad_token_id = tokenizer.eos_token_id
if model.config.pad_token_id is None or model.config.pad_token_id == -1:
model.config.pad_token_id = tokenizer.pad_token_id
model.generation_config.pad_token_id = model.config.pad_token_id
elif args.mode == "finetuning":
if args.model == "roberta":
if args.dataset == "glue_sts-b":
num_labels = 1
elif args.dataset == "glue_mnli":
num_labels = 3
else:
num_labels = 2
config = AutoConfig.from_pretrained(
"roberta-base",
num_labels=num_labels,
finetuning_task=arg_map[args.dataset][1],
)
if args.dtype == "bf16":
model = AutoModelForSequenceClassification.from_pretrained("roberta-base", torch_dtype=torch.bfloat16,
config=config)
else:
model = AutoModelForSequenceClassification.from_pretrained("roberta-base", config=config)
tokenizer = AutoTokenizer.from_pretrained("roberta-base")
# elif args.model == "gpt2":
# model = AutoModelForSequenceClassification.from_pretrained("gpt2", num_labels=2)
# tokenizer = AutoTokenizer.from_pretrained("gpt2", padding_side="left")
#
# tokenizer.pad_token = tokenizer.eos_token
# model.config.pad_token_id = tokenizer.pad_token_id
else:
raise ValueError("Invalid model name. Choose 'roberta' or 'gpt2'")
else:
raise ValueError("Invalid mode. Choose 'pretraining' or 'finetuning'")
if args.gradient_checkpointing == "true":
print("Gradient checkpointing enabled")
model.config.use_cache = False
model.gradient_checkpointing_enable()
return model, tokenizer
import json
from galore_torch import GaLoreAdamW, GaLoreAdamW8bit
from peft import LoraConfig, get_peft_model
from torch.optim import AdamW
import torch.nn as nn
from load_lr_scheduler import get_scheduler
def load_lora_config(args):
"""Loads LoRa configuration from file"""
if args.peft != "lora":
return LoraConfig(target_modules=[])
if args.lora_config is not None:
with open(args.lora_config, "r") as f:
lora_params = json.load(f)
else:
lora_params = {
"r": args.rank,
"lora_alpha": args.lora_alpha,
"lora_dropout": args.lora_dropout,
"target_modules_finetuning": ["query", "value"],
"target_modules_pretraining": ["q_proj", "v_proj"]
}
target_modules = lora_params["target_modules_finetuning"] if args.mode == "finetuning" else lora_params[
"target_modules_pretraining"]
return LoraConfig(
r=lora_params["r"],
lora_alpha=lora_params["lora_alpha"],
lora_dropout=lora_params["lora_dropout"],
target_modules=target_modules
)
def load_galore_config(args):
"""Loads GaLore configuration from file"""
if args.galore_config is not None:
with open(args.galore_config, "r") as f:
return json.load(f)
else:
return {
"rank": args.rank,
"update_proj_gap": args.galore_T,
"scale": args.galore_alpha,
"proj_type": "std"
}
def get_optimizer(args, model, num_steps):
"""Creates optimizer (GaLore, LoRa, or baseline AdamW)"""
optimizer_classes = {
"adamw": AdamW,
"galore": GaLoreAdamW,
"galore8bit": GaLoreAdamW8bit,
}
def get_galore_param_ids():
# make parameters with "rank" to a single group, if param_name has "mlp" or "attn"
lora_modules = set(load_lora_config(args).target_modules)
galore_params = []
if args.model == "roberta":
target_modules_list = {"query", "value", "key", "intermediate.dense", "output.dense"} - lora_modules
else:
target_modules_list = {"q_proj", "v_proj", "up_proj", "down_proj", "gate_proj", "k_proj", "o_proj"} - lora_modules
for module_name, module in model.named_modules():
if not isinstance(module, nn.Linear):
continue
if not any(target_key in module_name for target_key in target_modules_list):
continue
galore_params.append(module.weight)
return [id(p) for p in galore_params]
def get_optimizer_params(params, id_galore_params=None):
if "galore" in args.optimizer.lower():
galore_config = load_galore_config(args)
# make parameters without "rank" to another group
galore_params = [p for p in params if id(p) in id_galore_params]
regular_params = [p for p in params if id(p) not in id_galore_params]
# then call galore_adamw
return [{'params': regular_params},
{'params': galore_params, **galore_config}]
else:
return params # AdamW
# Activate LoRA
if args.peft == "lora":
lora_config = load_lora_config(args)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# Get optimizer
default_lr = args.lr
trainable_params = [p for p in model.parameters() if p.requires_grad and p.dim() > 1]
optimizer_class = optimizer_classes[args.optimizer.lower()]
if "galore" in args.optimizer.lower():
id_galore_params = get_galore_param_ids()
else:
id_galore_params = None
if args.lomo.lower() == "false":
optimizer_params = get_optimizer_params(trainable_params, id_galore_params)
optimizer = optimizer_class(optimizer_params, lr=default_lr, weight_decay=args.weight_decay)
else: # LOMO - per-layer weight updates to save memory
optimizer_dict = {}
scheduler_dict = {}
for p in trainable_params:
optimizer_params = get_optimizer_params([p], id_galore_params)
# TODO Scheduler is called twice per update step - This is a hack
if "galore" in args.optimizer.lower():
optimizer_params[1]['update_proj_gap'] *= 2
optimizer_dict[p] = optimizer_class(optimizer_params, lr=args.lr, weight_decay=args.weight_decay)
scheduler_dict[p] = get_scheduler(
optimizer=optimizer_dict[p],
scheduler_type=args.lr_scheduler,
num_steps=num_steps * 2, # TODO Scheduler is called twice per update step
warm_up_fraction=args.warm_up_fraction,
max_lr=args.lr,
min_lr=args.lr_min,
)
def optimizer_hook(p):
if p.grad is None:
return
optimizer_dict[p].step()
optimizer_dict[p].zero_grad()
scheduler_dict[p].step()
# Register the hook onto every parameter
for p in trainable_params:
p.register_post_accumulate_grad_hook(optimizer_hook)
optimizer = optimizer_dict
return optimizer, model
import torch
import psutil
import csv
import math
import datetime
from args import args
NOW_STRING = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
OPTIMIZER_STRING = args.optimizer
if args.peft == "lora":
OPTIMIZER_STRING += "+lora"
if args.lomo == "true":
OPTIMIZER_STRING += "+lomo"
BATCH_SIZE_STRING = f"batch-size-{args.batch_size}"
CSV_FILE = f"output_{args.mode}_{args.model}_{args.dataset}_{BATCH_SIZE_STRING}_{OPTIMIZER_STRING}_{NOW_STRING}.csv"
def init_csv():
"""Initialize CSV file with headers."""
with open(CSV_FILE, mode="w", newline="") as file:
writer = csv.writer(file)
line = ["epoch", "training_step", "compute_time",
"peak_memory_usage_allocated_GB", "peak_memory_usage_reserved_GB",
"training_loss", "evaluation_loss", "evaluation_metric"]
print(line)
writer.writerow(line)
def measure_memory():
"""Measure memory usage from CUDA or CPU."""
if torch.cuda.is_available():
torch.cuda.synchronize()
max_allocated = torch.cuda.max_memory_allocated() / 1e9
max_reserved = torch.cuda.max_memory_reserved() / 1e9
else:
mem = psutil.virtual_memory()
max_allocated = mem.used / 1e9
max_reserved = mem.total / 1e9 # Total system memory
return max_allocated, max_reserved
def log_to_csv(epoch, step, compute_time, train_loss, eval_loss, eval_metric):
"""Log training metrics to CSV file."""
max_allocated, max_reserved = measure_memory()
if isinstance(eval_loss, torch.Tensor):
eval_loss = eval_loss.item()
with open(CSV_FILE, mode="a", newline="") as file:
writer = csv.writer(file)
line = [epoch, step, compute_time, max_allocated, max_reserved,
train_loss, eval_loss, eval_metric]
writer.writerow(line)
torch.cuda.reset_peak_memory_stats()
from load_data import get_dataloader, arg_map
from load_models import get_model
from load_optimizers import get_optimizer
from load_lr_scheduler import get_scheduler
from logger import init_csv, log_to_csv
from accelerate import Accelerator
import torch
from evaluate import load
from args import args
from time import perf_counter
import warnings
warnings.filterwarnings("ignore", message="None of the inputs have requires_grad=True")
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.utils.checkpoint")
def train(scheduler, model, optimizer, train_dataloader, eval_dataloader, num_epochs):
""" training model """
model.train()
for epoch in range(num_epochs):
total_loss = 0
batch_cnt = 0
compute_time = 0
for step, batch in enumerate(train_dataloader):
if args.num_training_steps is not None and args.num_training_steps <= batch_cnt:
break
batch = {key: value.to(device) for key, value in batch.items()}
start_time = perf_counter()
outputs = model(**batch)
loss = outputs.loss
loss = loss / args.gradient_accumulation_steps
accelerator.backward(loss)
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.lomo.lower() == "false":
# For LOMO, the optimizer hooks take care of this
optimizer.step()
scheduler.step()
optimizer.zero_grad()
batch_cnt += 1
compute_time += perf_counter() - start_time
if batch_cnt % args.eval_every == 0 and (step + 1) % args.gradient_accumulation_steps == 0:
train_loss = loss.item()
eval_loss, eval_mertic = evaluate(accelerator, model, eval_dataloader)
log_to_csv(epoch + 1, batch_cnt, compute_time / args.eval_every, train_loss, eval_loss, eval_mertic)
compute_time = 0
total_loss += loss.item()
# avg_loss = total_loss / max(1, batch_cnt)
# print(f"Epoch {epoch+1}, Avg. training loss: {avg_loss:.4f}")
torch.cuda.empty_cache()
return model
def evaluate(accelerator, model, eval_dataloader):
if args.mode == "finetuning":
metric = load(*arg_map[args.dataset])
else:
metric = None # TODO Metric fro pretraining
# model.eval()
total_loss = torch.tensor(0.0).to(device)
num_batches = len(train_dataloader) if args.num_training_steps is None else args.num_training_steps
# eval_dataloader.batch = lambda batch_size: training_utils.batch_fn(eval_dataloader, batch_size)
# for batch in eval_dataloader.batch(batch_size=args.batch_size):
for step, batch in enumerate(eval_dataloader):
if args.num_eval_steps is not None and args.num_eval_steps <= step:
break
batch = {key: value.to(device) for key, value in batch.items()}
if args.mode == "finetuning":
is_regression = args.dataset == "glue_sts-b"
labels = batch["labels"]
with torch.no_grad():
outputs = model(**batch)
predictions = outputs.logits.argmax(dim=-1) if not is_regression else outputs.logits.squeeze()
predictions, references = accelerator.gather((predictions, labels))
metric.add_batch(
predictions=predictions,
references=references,
)
else:
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
total_loss += loss.detach()
mean_loss = total_loss / num_batches
if args.mode == "finetuning":
eval_metric = metric.compute()
else:
eval_metric = torch.exp(mean_loss.clone().detach()).item() # perplexity
return total_loss, eval_metric
if __name__ == "__main__":
if args.test == "true":
print("Test mode")
accelerator = Accelerator()
else:
accelerator = Accelerator(mixed_precision="bf16")
device = accelerator.device
print(f"Running on: {device}")
print(f"Using optimizer: {args.optimizer}")
print(f"Arguments: {args}")
# Load stuff
model, tokenizer = get_model(args)
train_dataloader, eval_dataloader = get_dataloader(args, tokenizer)
# Init setup
num_batches = len(train_dataloader) if args.num_training_steps is None else args.num_training_steps
num_steps = args.num_epochs * num_batches
optimizer, model = get_optimizer(args, model, num_steps)
if args.lomo.lower() == "false":
lr_scheduler = get_scheduler(
optimizer, args.lr_scheduler, args.warm_up_fraction, num_steps, args.lr, args.lr_min
)
else:
lr_scheduler = None
# Prepare everything with our `accelerator`.
# TODO Replace accelerator to enable LOMO?
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
)
# Train
init_csv()
trained_model = train(
lr_scheduler, model, optimizer, train_dataloader, eval_dataloader, args.num_epochs
)
# Evaluate
file_name = f"{args.model}_{args.optimizer}_pretrained" if args.mode == "pretraining" else f"{args.model}_{args.optimizer}_finetuned"
model_path = f"models/{file_name}"
trained_model.save_pretrained(model_path)
tokenizer.save_pretrained(model_path)
\ No newline at end of file