-
Notifications
You must be signed in to change notification settings - Fork 32
Feat/add gemma4 support #199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EvineR666
wants to merge
4
commits into
modelscope:main
Choose a base branch
from
EvineR666:feat/add-gemma4-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2df1bb7
feat: gemma4 support initial commit (WIP)
EvineR666 854a867
fix: resolve multimodal data handling bug in Template messages
EvineR666 dccd0c5
fix: correct some spelling errors
EvineR666 e967689
refactor: move _build_standard_messages to base Template
EvineR666 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| import os | ||
| from peft import LoraConfig | ||
| from tqdm import tqdm | ||
| from transformers import AutoConfig | ||
| from transformers import ( | ||
| Gemma4Config, | ||
| ) | ||
|
|
||
| import twinkle | ||
| from twinkle import DeviceMesh, Platform, get_device_placement, get_logger | ||
| from twinkle.dataloader import DataLoader | ||
| from twinkle.dataset import Dataset, DatasetMeta | ||
| from twinkle.model import TransformersModel | ||
| # from twinkle.preprocessor import SelfCognitionProcessor, LatexOCRProcessor | ||
|
|
||
| logger = get_logger() | ||
|
|
||
| ########## Construct a device_mesh ########## | ||
| device_mesh = DeviceMesh.from_sizes( | ||
| # fsdp_size=2, | ||
| # dp_size=1, | ||
| # ep_size=2, | ||
| device_type=Platform.get_platform().device_prefix(), | ||
| ) | ||
| # use torchrun mode | ||
| twinkle.initialize(mode='local', global_device_mesh=device_mesh) | ||
|
|
||
| ########## hyperparameters ########## | ||
| IGNORE_MISMATCHED_SIZES = True | ||
| MODEL_PATH = 'ms://google/gemma-4-26b-a4b' | ||
| DATASET_PATH = 'ms://AI-ModelScope/LaTeX_OCR' | ||
| TRAIN_LEN = 2000 | ||
| BATCH_SIZE = 4 | ||
| METRIC_STEP = 10 | ||
| SAVE_STEP = 10 | ||
|
|
||
| ### reduce model layers for debug | ||
| TEXT_NUM_LAYERS = 3 | ||
| VISION_NUM_LAYERS = 3 | ||
|
|
||
|
|
||
| from twinkle.preprocessor import Preprocessor | ||
| from twinkle.data_format import Message, Trajectory | ||
| class LatexOCRProcessor(Preprocessor): | ||
|
|
||
| def __call__(self, rows): | ||
| rows = self.map_col_to_row(rows) | ||
| rows = [self.preprocess(row) for row in rows] | ||
| col = self.map_row_to_col(rows) | ||
| return col | ||
|
|
||
| def preprocess(self, row) -> Trajectory: | ||
| return Trajectory( | ||
| messages=[ | ||
| Message(role='user', content='<image>Using LaTeX to perform OCR on the image.', images=[row['image']]), | ||
| Message(role='assistant', content=row['text']), | ||
| ] | ||
| ) | ||
|
|
||
| def eval(model, eval_dataloader): | ||
| for step, batch in tqdm(enumerate(eval_dataloader)): | ||
| model.forward_only(inputs=batch) | ||
| model.calculate_loss() | ||
| metrics = model.calculate_metric(is_training=False) | ||
| return metrics | ||
|
|
||
| def train(): | ||
|
|
||
| ### prepare dataset and dataloader | ||
| dataset = Dataset(dataset_meta=DatasetMeta(DATASET_PATH, data_slice=range(TRAIN_LEN))) | ||
| # Set template to prepare encoding | ||
| dataset.set_template('Gemma4Template', model_id=MODEL_PATH) | ||
| # Preprocess the dataset to standard format | ||
| # dataset.map(preprocess_func=SelfCognitionProcessor('twinkle大模型', 'ModelScope社区')) | ||
| dataset.map(preprocess_func=LatexOCRProcessor) | ||
| # Encode dataset | ||
| dataset.encode() | ||
| dataloader = DataLoader(dataset=dataset, batch_size=BATCH_SIZE) | ||
|
|
||
| config, kwargs = AutoConfig.from_pretrained( | ||
| MODEL_PATH, | ||
| trust_remote_code=True, | ||
| return_unused_kwargs=True, | ||
| # code_revision=code_revision, | ||
| # _commit_hash=commit_hash, | ||
| # **hub_kwargs, | ||
| # **kwargs, | ||
| ) | ||
|
|
||
| if isinstance(config, Gemma4Config): # 减层 | ||
| text_config = config.text_config | ||
| vision_config = config.vision_config | ||
| if TEXT_NUM_LAYERS is not None and hasattr(text_config, 'num_hidden_layers'): | ||
| text_config.num_hidden_layers = TEXT_NUM_LAYERS | ||
| logger.info(f" modify > text_config.num_hidden_layers = {text_config.num_hidden_layers}") | ||
| if VISION_NUM_LAYERS is not None and hasattr(vision_config, 'num_hidden_layers'): | ||
| vision_config.num_hidden_layers = VISION_NUM_LAYERS | ||
| logger.info(f" modify > vision_config.num_hidden_layers = {vision_config.num_hidden_layers}") | ||
| if hasattr(config, 'use_cache'): | ||
| config.use_cache = False | ||
|
|
||
| # Use a TransformersModel | ||
| model = TransformersModel( | ||
| model_id=MODEL_PATH, | ||
| config=config, | ||
| device_mesh=device_mesh, | ||
| strategy="accelerate", # native_fsdp、 accelerate | ||
| ignore_mismatched_sizes=IGNORE_MISMATCHED_SIZES, | ||
| fsdp_config={ | ||
| 'reshard_after_forward': True, | ||
| 'expert_parallel': { | ||
| 'enabled': True, | ||
| 'router_dtype': 'fp32', | ||
| 'keep_router_logits': False, | ||
| } | ||
| }, | ||
| ) | ||
| # 若未传入config, 则自动通过 AutoConfig.from_pretrained 读取config | ||
|
|
||
| # model.model._no_split_modules = {'Gemma4VisionEncoderLayer', 'Gemma4TextDecoderLayer', 'Gemma4AudioLayer'} # for 3 modalities(2B、4B) | ||
| # model.model._no_split_modules = {'Gemma4VisionEncoderLayer', 'Gemma4TextDecoderLayer'} # for 2 modalities(26B-A4B、31B) | ||
|
|
||
| lora_config = LoraConfig(r=8, lora_alpha=32, target_modules='all-linear') | ||
|
|
||
| # Add a lora to model, with name `default` | ||
| # Comment this to use full-parameter training | ||
| model.add_adapter_to_model('default', lora_config, gradient_accumulation_steps=2) | ||
| # Add Optimizer for lora `default` | ||
| model.set_optimizer(optimizer_cls='AdamW', lr=1e-4) | ||
|
|
||
| # Add LRScheduler for lora `default` | ||
| model.set_lr_scheduler( | ||
| scheduler_cls='CosineWarmupScheduler', num_warmup_steps=5, num_training_steps=len(dataloader)) | ||
|
|
||
| logger.info(get_device_placement()) | ||
| # Print the training config | ||
| logger.info(model.get_train_configs()) | ||
| logger.info(f'Total steps: {len(dataloader)}') | ||
| best_eval_loss = float('inf') | ||
| # lora: 8G * 8 | ||
| # full: 18G * 8 | ||
|
|
||
| ### eval dataset and dataloader | ||
| EVAL_LENGTH = 100 | ||
| eval_dataset = Dataset(dataset_meta=DatasetMeta(DATASET_PATH, data_slice=range(EVAL_LENGTH))) | ||
| eval_dataset.set_template('Gemma4Template', model_id=MODEL_PATH) | ||
| # eval_dataset.map(preprocess_func=SelfCognitionProcessor('twinkle大模型', 'ModelScope社区')) | ||
| eval_dataset.map(preprocess_func=LatexOCRProcessor) | ||
| eval_dataset.encode() | ||
| eval_dataloader = DataLoader(dataset=eval_dataset, batch_size=8) | ||
| for step, batch in tqdm(enumerate(dataloader), total=len(dataloader)): | ||
| # Do forward and backward | ||
| model.forward_backward(inputs=batch) | ||
| # Step | ||
| model.clip_grad_and_step() | ||
|
|
||
| if step % METRIC_STEP == 0: | ||
| # Print metric | ||
| metric = model.calculate_metric(is_training=True) | ||
| logger.info(f'Current is step {step} of {len(dataloader)}, Train metric: {metric}') | ||
|
|
||
| if step % SAVE_STEP == 0: | ||
| metrics = eval(model, eval_dataloader) | ||
| metrics['step'] = step | ||
| if float(metrics['loss']) < best_eval_loss: | ||
| # model.save(f'checkpoint-{step}') | ||
| best_eval_loss = float(metrics['loss']) | ||
| metrics['best_eval_loss'] = best_eval_loss | ||
| logger.info(f'Current is step {step} of {len(dataloader)}, Eval metric: {metrics}') | ||
|
|
||
| # model.save(f'last-checkpoint') | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| train() | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export CUDA_VISIBLE_DEVICES=0,1 | ||
|
|
||
| torchrun --nnodes=1 --nproc_per_node=2 fsdp2_gemma4_mm.py |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| # Copyright (c) ModelScope Contributors. All rights reserved. | ||
| from .base import Template | ||
| from .qwen3_5_vl import Qwen3_5Template | ||
| from .gemma4 import Gemma4Template |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
|
|
||
| from typing import List | ||
| from twinkle import remote_class | ||
| from twinkle.template import Template | ||
| from twinkle.data_format import Trajectory | ||
|
|
||
| @remote_class() | ||
| class Gemma4Template(Template): | ||
| """Processor for Google Gemma4 series.""" | ||
|
|
||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
| # use original Template | ||
|
|
||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个类是否有存在的必要