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

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
Show changes
Commits on Source (29)
Showing with 466 additions and 86 deletions
__pycache__
test.py
output.txt
output.csv
models/
.idea/
venv/
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (galore-replication (GitLab))" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/galore-replication (GitLab).iml" filepath="$PROJECT_DIR$/.idea/galore-replication (GitLab).iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
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_1b", "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=["lora", "galore", "galore8bit", "lora+galore8bit", "baseline"], required=True, help="Optimizer type to use")
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("--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": 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),
}
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 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.")
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)
# in the galore project they say:
# "it doesn't matter which tokenizer we use, because we train from scratch
# T5 tokenizer was trained on C4 and we are also training on C4, so it's a good choice"
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":
num_labels = 1 if args.dataset == "glue_stsb" else 2 # TODO might be wrong
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'")
return model, tokenizer
from galore_torch import GaLoreAdamW, GaLoreAdamW8bit
from peft import LoraConfig, get_peft_model
from torch.optim import AdamW
import json
def load_lora_config(args):
"""Loads LoRa configuration from file"""
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):
"""Creates optimizer (GaLore, LoRa, or baseline AdamW)"""
default_lr = args.lr
if args.optimizer == "baseline":
return AdamW(model.parameters(), lr=default_lr, weight_decay=args.weight_decay), model
elif args.optimizer in ["galore", "galore8bit"]:
galore_config = load_galore_config(args)
trainable_params = [p for p in model.parameters() if p.requires_grad and p.dim() > 1]
param_groups = [
{"params": trainable_params, **galore_config}
]
optimizer_class = GaLoreAdamW if args.optimizer == "galore" else GaLoreAdamW8bit
return optimizer_class(param_groups, lr=default_lr, weight_decay=args.weight_decay), model
elif args.optimizer in ["lora", "lora+galore8bit"]:
lora_config = load_lora_config(args)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
if args.optimizer == "lora":
return AdamW(model.parameters(), lr=args.lr), model
else:
galore_config = load_galore_config(args)
trainable_params = [p for p in model.parameters() if p.requires_grad and p.dim() > 1]
param_groups = [
{"params": trainable_params, **galore_config}
]
return GaLoreAdamW8bit(param_groups, lr=default_lr, weight_decay=args.weight_decay), model
else:
raise ValueError(f"Unknown optimizer: {args.optimizer}")
\ No newline at end of file