rpeft 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,31 @@
1
1
  import json
2
+ import sys
2
3
 
3
4
  from . import _chat
4
5
  from ._errors import BackendError, stage
5
6
 
7
+ IGNORED = -100
6
8
 
7
- def load_tokenized_dataset(path, tokenizer, text_field, max_length, dataset_format="text"):
9
+ # The record fields each backend format reads. text_field stands in for the configurable text column.
10
+ FIELDS = {"text": ("text_field",), "completion": ("prompt", "completion"), "messages": ("messages",)}
11
+
12
+
13
+ def load_tokenized_dataset(
14
+ path, tokenizer, text_field, max_length, dataset_format="text", train_on_prompt=False, name="dataset"
15
+ ):
16
+ """Returns the tokenized dataset and the number of examples left out of it.
17
+
18
+ Every example carries its own labels: the prompt positions hold IGNORED unless train_on_prompt is set,
19
+ so the loss covers only what the model is meant to write. name tells the datasets apart in messages.
20
+ """
8
21
  with stage("dataset"):
9
22
  from datasets import Dataset
10
23
 
11
24
  # Built in memory rather than with load_dataset("json", ...), which writes an Arrow copy of every
12
25
  # file into the Hugging Face cache. Each run reads a fresh file, so that copy would never be reused.
13
- dataset = Dataset.from_list(_read_jsonl(path))
14
- field = "messages" if dataset_format == "messages" else text_field
15
- if field not in dataset.column_names:
16
- raise BackendError(
17
- "dataset",
18
- "field '%s' not found in dataset (available: %s)"
19
- % (field, ", ".join(dataset.column_names)),
20
- )
26
+ records = _read_jsonl(path)
27
+ fields = [text_field if field == "text_field" else field for field in FIELDS[dataset_format]]
28
+ _check_fields(records, fields)
21
29
 
22
30
  add_special_tokens = not (dataset_format == "messages" and _chat.writes_special_tokens(tokenizer))
23
31
  # A chat template closes every turn with its own end marker. Plain text has none, so without an EOS
@@ -25,25 +33,95 @@ def load_tokenized_dataset(path, tokenizer, text_field, max_length, dataset_form
25
33
  eos = tokenizer.eos_token_id if dataset_format != "messages" else None
26
34
  content_length = max_length - 1 if eos is not None else max_length
27
35
 
28
- def tokenize(batch):
29
- if dataset_format == "messages":
30
- texts = [_chat.render(tokenizer, messages) for messages in batch[field]]
31
- else:
32
- texts = batch[field]
36
+ examples = []
37
+ for record in records:
38
+ segments = _segments(tokenizer, record, dataset_format, fields, train_on_prompt)
39
+ example = _encode(tokenizer, segments, add_special_tokens, content_length, train_on_prompt, eos)
40
+ if example is not None:
41
+ examples.append(example)
33
42
 
34
- # No padding here: the collator pads each batch dynamically.
35
- encoded = tokenizer(
36
- texts, truncation=True, max_length=content_length, add_special_tokens=add_special_tokens
37
- )
38
- if eos is not None:
39
- for input_ids, attention_mask in zip(encoded["input_ids"], encoded["attention_mask"]):
40
- input_ids.append(eos)
41
- attention_mask.append(1)
42
- return encoded
43
-
44
- return dataset.map(
45
- tokenize, batched=True, remove_columns=dataset.column_names, keep_in_memory=True
43
+ skipped = len(records) - len(examples)
44
+ reason = (
45
+ "no answer left to train on: a transcript without an assistant reply after its first message, "
46
+ "or an answer cut off by max_length %d" % max_length
46
47
  )
48
+ if not examples:
49
+ raise BackendError("dataset", "every example in %s has %s" % (name, reason))
50
+ if skipped:
51
+ print(
52
+ "rpeft: skipped %d of %d examples in %s with %s" % (skipped, len(records), name, reason),
53
+ file=sys.stderr,
54
+ )
55
+
56
+ return Dataset.from_list(examples), skipped
57
+
58
+
59
+ def _check_fields(records, fields):
60
+ available = set()
61
+ for record in records:
62
+ available.update(record)
63
+ for field in fields:
64
+ if field not in available:
65
+ raise BackendError(
66
+ "dataset",
67
+ "field '%s' not found in dataset (available: %s)" % (field, ", ".join(sorted(available))),
68
+ )
69
+
70
+
71
+ def _segments(tokenizer, record, dataset_format, fields, train_on_prompt):
72
+ # (text, trainable) pairs whose concatenation is the whole example.
73
+ if dataset_format == "messages":
74
+ if train_on_prompt:
75
+ return [(_chat.render(tokenizer, record[fields[0]]), True)]
76
+ return _chat.segments(tokenizer, record[fields[0]])
77
+ if dataset_format == "completion":
78
+ return [(record[fields[0]], False), (record[fields[1]], True)]
79
+ return [(record[fields[0]], True)]
80
+
81
+
82
+ def _encode(tokenizer, segments, add_special_tokens, content_length, train_on_prompt, eos):
83
+ def tokenize(text):
84
+ return tokenizer(
85
+ text, truncation=True, max_length=content_length, add_special_tokens=add_special_tokens
86
+ )["input_ids"]
87
+
88
+ # The example is tokenized as a whole, so every token is the one the model sees in the full text.
89
+ # Tokenizing segments one by one would not do: a SentencePiece tokenizer marks the start of each piece
90
+ # with a space, turning an answer "hello" into " hello". A segment ends where the text up to its end,
91
+ # tokenized on its own as the prompt is at inference, stops matching the whole.
92
+ text = "".join(segment for segment, _ in segments)
93
+ input_ids = tokenize(text)
94
+ labels = []
95
+ answers = []
96
+ start = 0
97
+ offset = 0
98
+ for segment, trainable in segments:
99
+ offset += len(segment)
100
+ end = len(input_ids) if offset == len(text) else max(start, _common_prefix(tokenize(text[:offset]), input_ids))
101
+ ids = input_ids[start:end]
102
+ labels.extend(ids if trainable or train_on_prompt else [IGNORED] * len(ids))
103
+ answers.extend([trainable] * len(ids))
104
+ start = end
105
+
106
+ if eos is not None:
107
+ input_ids.append(eos)
108
+ labels.append(eos)
109
+
110
+ # Without prompt training, an answer cut away entirely leaves an example that teaches nothing but to stop.
111
+ answer_cut_away = any(trainable and segment for segment, trainable in segments) and not any(answers)
112
+ if (not train_on_prompt and answer_cut_away) or all(label == IGNORED for label in labels):
113
+ return None
114
+
115
+ return {"input_ids": input_ids, "attention_mask": [1] * len(input_ids), "labels": labels}
116
+
117
+
118
+ def _common_prefix(ids, other):
119
+ length = 0
120
+ for left, right in zip(ids, other):
121
+ if left != right:
122
+ break
123
+ length += 1
124
+ return length
47
125
 
48
126
 
49
127
  def _read_jsonl(path):
@@ -21,22 +21,11 @@ def train_lora(config):
21
21
  device=device,
22
22
  trust_remote_code=config.get("trust_remote_code", False),
23
23
  )
24
- dataset = _data.load_tokenized_dataset(
25
- config["dataset_path"],
26
- tokenizer,
27
- text_field=config.get("text_field", "text"),
28
- max_length=config.get("max_length", 512),
29
- dataset_format=config.get("dataset_format", "text"),
30
- )
24
+ dataset, skipped = _load_dataset(config, tokenizer, "dataset")
31
25
  eval_dataset = None
26
+ eval_skipped = None
32
27
  if config.get("eval_dataset_path"):
33
- eval_dataset = _data.load_tokenized_dataset(
34
- config["eval_dataset_path"],
35
- tokenizer,
36
- text_field=config.get("text_field", "text"),
37
- max_length=config.get("max_length", 512),
38
- dataset_format=config.get("dataset_format", "text"),
39
- )
28
+ eval_dataset, eval_skipped = _load_dataset(config, tokenizer, "eval_dataset")
40
29
 
41
30
  with stage("training"):
42
31
  model, target_modules, param_counts = _apply_lora(model, lora)
@@ -54,7 +43,7 @@ def train_lora(config):
54
43
  shutil.rmtree(_trainer_dir(output_dir), ignore_errors=True)
55
44
 
56
45
  return _result(
57
- config, device, dtype, target_modules, param_counts, metrics, steps, len(dataset)
46
+ config, device, dtype, target_modules, param_counts, metrics, steps, len(dataset), skipped, eval_skipped
58
47
  )
59
48
  finally:
60
49
  model = None
@@ -62,6 +51,18 @@ def train_lora(config):
62
51
  _device.empty_cache(device)
63
52
 
64
53
 
54
+ def _load_dataset(config, tokenizer, name):
55
+ return _data.load_tokenized_dataset(
56
+ config[name + "_path"],
57
+ tokenizer,
58
+ text_field=config.get("text_field", "text"),
59
+ max_length=config.get("max_length", 512),
60
+ dataset_format=config.get(name + "_format") or config.get("dataset_format", "text"),
61
+ train_on_prompt=bool(config.get("train_on_prompt", False)),
62
+ name=name,
63
+ )
64
+
65
+
65
66
  def _apply_lora(model, lora):
66
67
  from peft import LoraConfig, TaskType, get_peft_model
67
68
 
@@ -117,7 +118,7 @@ def _build_trainer(model, tokenizer, dataset, eval_dataset, config, device, dtyp
117
118
  )
118
119
 
119
120
 
120
- def _result(config, device, dtype, target_modules, param_counts, metrics, steps, num_examples):
121
+ def _result(config, device, dtype, target_modules, param_counts, metrics, steps, num_examples, skipped, eval_skipped):
121
122
  trainable_params, total_params = param_counts
122
123
  effective = dict(config)
123
124
  effective["device"] = device
@@ -133,6 +134,8 @@ def _result(config, device, dtype, target_modules, param_counts, metrics, steps,
133
134
  "final_loss": float(metrics.get("train_loss", 0.0)),
134
135
  "eval_loss": float(metrics["eval_loss"]) if "eval_loss" in metrics else None,
135
136
  "num_examples": int(num_examples),
137
+ "skipped_examples": int(skipped),
138
+ "eval_skipped_examples": int(eval_skipped) if eval_skipped is not None else None,
136
139
  "steps": int(steps),
137
140
  "trainable_params": int(trainable_params),
138
141
  "total_params": int(total_params),
@@ -156,15 +159,23 @@ def _resume_point(config):
156
159
 
157
160
 
158
161
  def _collator(tokenizer):
159
- # DataCollatorForLanguageModeling ignores every position holding the pad token. Tokenizers without
160
- # a pad token of their own pad with EOS (see _models.load_tokenizer), and many that have one reuse
161
- # EOS too, so the EOS that ends each example would never be learned. Only the padding the batch
162
- # added is ignored here, found through the attention mask instead of the token id.
162
+ # Labels come with each example rather than from the pad token id, as DataCollatorForLanguageModeling
163
+ # derives them. Tokenizers without a pad token of their own pad with EOS (see _models.load_tokenizer),
164
+ # and many that have one reuse EOS too, so the EOS that ends each example would never be learned.
163
165
  def collate(features):
164
- batch = tokenizer.pad(features, return_tensors="pt")
165
- labels = batch["input_ids"].clone()
166
- labels[batch["attention_mask"] == 0] = -100
167
- batch["labels"] = labels
166
+ import torch
167
+
168
+ labels = [list(feature["labels"]) for feature in features]
169
+ batch = tokenizer.pad(
170
+ [{key: value for key, value in feature.items() if key != "labels"} for feature in features],
171
+ return_tensors="pt",
172
+ )
173
+ width = batch["input_ids"].shape[1]
174
+ padded = []
175
+ for example in labels:
176
+ padding = [_data.IGNORED] * (width - len(example))
177
+ padded.append(padding + example if tokenizer.padding_side == "left" else example + padding)
178
+ batch["labels"] = torch.tensor(padded, dtype=torch.long)
168
179
  return batch
169
180
 
170
181
  return collate
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rpeft
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Koichi ITO
@@ -60,6 +60,7 @@ files:
60
60
  - lib/rpeft/cli.rb
61
61
  - lib/rpeft/cli/command.rb
62
62
  - lib/rpeft/cli/doctor.rb
63
+ - lib/rpeft/cli/export_gguf.rb
63
64
  - lib/rpeft/cli/generate.rb
64
65
  - lib/rpeft/cli/lora_merge.rb
65
66
  - lib/rpeft/cli/lora_train.rb
@@ -69,6 +70,7 @@ files:
69
70
  - lib/rpeft/directory.rb
70
71
  - lib/rpeft/errors.rb
71
72
  - lib/rpeft/generation.rb
73
+ - lib/rpeft/gguf.rb
72
74
  - lib/rpeft/lora.rb
73
75
  - lib/rpeft/lora/adapter.rb
74
76
  - lib/rpeft/messages.rb
@@ -107,7 +109,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
107
109
  - !ruby/object:Gem::Version
108
110
  version: '0'
109
111
  requirements: []
110
- rubygems_version: 4.0.16
112
+ rubygems_version: 4.0.20
111
113
  specification_version: 4
112
114
  summary: LoRA fine-tuning for LLMs from Ruby.
113
115
  test_files: []