ZHZisZZ commited on
Commit
fed1f43
·
1 Parent(s): 304c27e

sft init save

Browse files
cua_lite/train/collators.py CHANGED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ from transformers import ProcessorMixin
5
+ from transformers.data.data_collator import DataCollatorMixin
6
+
7
+
8
+ def insert_images_into_messages(messages, images):
9
+ # Use an iterator to avoid manual index management; this is more Pythonic
10
+ images_iter = iter(images)
11
+
12
+ for message in messages:
13
+ # Skip messages that are not from the user
14
+ if message["role"] != "user":
15
+ continue
16
+
17
+ # 1. Normalization Logic
18
+ # (Convert string content to list format if necessary)
19
+ if isinstance(message["content"], str):
20
+ message["content"] = [{"type": "text", "text": message["content"]}]
21
+ # Strings cannot contain image placeholders, so skip the rest of the loop
22
+ continue
23
+
24
+ # 2. Image Injection Logic
25
+ for item in message["content"]:
26
+ if item.get("type") == "image":
27
+ try:
28
+ # Get the next image and update the dictionary in-place
29
+ item["image"] = next(images_iter)
30
+ except StopIteration:
31
+ raise ValueError("Not enough images provided for the placeholders in messages.")
32
+
33
+ # 3. Validation: Check for surplus images
34
+ # If the iterator still has items, it means too many images were provided
35
+ if next(images_iter, None) is not None:
36
+ raise ValueError(f"Too many images provided. Total provided: {len(images)}")
37
+
38
+ return messages
39
+
40
+ def phantomize_images_in_messages(messages):
41
+ for message in messages:
42
+ if message["role"] == "user":
43
+ if isinstance(message["content"], list):
44
+ for i in range(len(message["content"])):
45
+ if message["content"][i]["type"] == "image":
46
+ message["content"][i] = {"type": "image"}
47
+ return messages
48
+
49
+ @dataclass
50
+ class DataCollatorForVisionLanguageModeling(DataCollatorMixin):
51
+ processor: ProcessorMixin
52
+ max_length: int | None = None
53
+ completion_only_loss: bool = False # default not used in practice; SFTTrainer always passes the relevant value
54
+ pad_to_multiple_of: int | None = None
55
+ dataset_text_field: str = "text"
56
+ return_tensors: str = "pt"
57
+
58
+ def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
59
+ assert "messages" in examples[0]
60
+ assert all(example["messages"][-1]["role"] == "assistant" for example in examples)
61
+ if "images" in examples[0]:
62
+ # merge images into messages
63
+ for example in examples:
64
+ insert_images_into_messages(example["messages"], example["images"])
65
+ example.pop("images")
66
+
67
+ apply_chat_template_kwargs = dict(
68
+ tokenize=True,
69
+ padding=True,
70
+ padding_side="right",
71
+ pad_to_multiple_of=self.pad_to_multiple_of,
72
+ truncation=self.max_length is not None,
73
+ max_length=self.max_length,
74
+ return_dict=True,
75
+ return_tensors=self.return_tensors,
76
+ add_special_tokens=False, # to avoid adding the BOS, twice see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens
77
+ )
78
+
79
+ output = self.processor.apply_chat_template(
80
+ [example["messages"] for example in examples],
81
+ **apply_chat_template_kwargs,
82
+ )
83
+
84
+ labels = output["input_ids"].clone()
85
+
86
+ # mask labels not belonging to the last turn response
87
+ if self.completion_only_loss:
88
+ # TODO: remove redundant image processing
89
+ non_completion_output = self.processor.apply_chat_template(
90
+ [example["messages"][:-1] for example in examples],
91
+ add_generation_prompt=True,
92
+ **apply_chat_template_kwargs,
93
+ )
94
+ for i in labels.size(0):
95
+ labels[i, :sum(non_completion_output["attention_mask"][i])] = -100
96
+
97
+ labels[output["attention_mask"] == 0] = -100
98
+ # We mask only padding tokens (-100) in the labels. Vision tokens are left unchanged because their handling in
99
+ # loss computation has to be done by the model, and masking them here would be infeasible in practice as vision
100
+ # token definitions vary across architectures.
101
+ output["labels"] = labels
102
+ return output
103
+
104
+
105
+ if __name__ == "__main__":
106
+ from datasets import load_dataset
107
+ from transformers import AutoProcessor
108
+
109
+ from cua_lite.utils import resolve_with_base_env
110
+ from trl.trainer import sft_trainer
111
+
112
+ dataset_path = "HuggingFaceH4/llava-instruct-mix-vsft"
113
+ dataset_path = resolve_with_base_env(dataset_path, "BASE_DATASETS_DIR")
114
+ dataset = load_dataset(dataset_path)
115
+
116
+ processor_path = "Qwen/Qwen3-VL-2B-Thinking"
117
+ processor_path = resolve_with_base_env(processor_path, "BASE_MODELS_DIR")
118
+ processor = AutoProcessor.from_pretrained(processor_path)
119
+
120
+ collator = DataCollatorForVisionLanguageModeling(processor=processor, completion_only_loss=True)
121
+ output = collator([dataset["train"][0], dataset["train"][1]])
122
+
123
+ trl_collator = sft_trainer.DataCollatorForVisionLanguageModeling(processor=processor)
124
+ trl_output = collator([dataset["train"][0], dataset["train"][1]])
125
+ breakpoint()
cua_lite/train/sft.py CHANGED
@@ -58,8 +58,7 @@ import os
58
 
59
  import torch
60
  from datasets import load_dataset
61
- from transformers import AutoModelForImageTextToText
62
-
63
  from trl import (
64
  ModelConfig,
65
  ScriptArguments,
@@ -71,6 +70,8 @@ from trl import (
71
  get_quantization_config,
72
  )
73
 
 
 
74
 
75
  # Enable logging in a Hugging Face Space
76
  os.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio")
@@ -98,6 +99,9 @@ if __name__ == "__main__":
98
  model = AutoModelForImageTextToText.from_pretrained(
99
  model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
100
  )
 
 
 
101
 
102
  ################
103
  # Dataset
@@ -107,9 +111,16 @@ if __name__ == "__main__":
107
  ################
108
  # Training
109
  ################
 
 
 
 
 
 
110
  trainer = SFTTrainer(
111
  model=model,
112
  args=training_args,
 
113
  train_dataset=dataset[script_args.dataset_train_split],
114
  eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
115
  peft_config=get_peft_config(model_args),
 
58
 
59
  import torch
60
  from datasets import load_dataset
61
+ from transformers import AutoModelForImageTextToText, AutoProcessor
 
62
  from trl import (
63
  ModelConfig,
64
  ScriptArguments,
 
70
  get_quantization_config,
71
  )
72
 
73
+ from cua_lite.train.collators import DataCollatorForVisionLanguageModeling
74
+
75
 
76
  # Enable logging in a Hugging Face Space
77
  os.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio")
 
99
  model = AutoModelForImageTextToText.from_pretrained(
100
  model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
101
  )
102
+ processor = AutoProcessor.from_pretrained(
103
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code
104
+ )
105
 
106
  ################
107
  # Dataset
 
111
  ################
112
  # Training
113
  ################
114
+ data_collator = DataCollatorForVisionLanguageModeling(
115
+ processor=processor,
116
+ max_length=training_args.max_length,
117
+ completion_only_loss=training_args.completion_only_loss,
118
+ pad_to_multiple_of=training_args.pad_to_multiple_of,
119
+ )
120
  trainer = SFTTrainer(
121
  model=model,
122
  args=training_args,
123
+ data_collator=data_collator,
124
  train_dataset=dataset[script_args.dataset_train_split],
125
  eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
126
  peft_config=get_peft_config(model_args),
cua_lite/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from cua_lite.utils.utils import *
cua_lite/utils/utils.py CHANGED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ def resolve_with_base_env(path: str, env_name: str) -> str:
4
+ """
5
+ If `env_name` is set and `path` is NOT absolute, NOT a URL/scheme,
6
+ and does not already exist locally, prepend the `env_name` directory.
7
+
8
+ If the resulting path does not exist, return the base environment directory instead.
9
+ Otherwise return `path` unchanged.
10
+ """
11
+ base = os.getenv(env_name, "").strip()
12
+ if not base:
13
+ return path
14
+ if os.path.isabs(path):
15
+ return path
16
+ if os.path.exists(path):
17
+ return path
18
+
19
+ candidate = os.path.join(base.rstrip("/"), path.lstrip("/"))
20
+ if os.path.exists(candidate):
21
+ return candidate
22
+ else:
23
+ raise FileNotFoundError