rpeft 0.3.0 → 0.4.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e72e65f59460cc4217035e8043cf25d6e2b1514638fd20589cdcf6949a9508ab
4
- data.tar.gz: aeacf67c2210d3dc50508e21741badf255015cdcabcde184e8c51d1f83433b6f
3
+ metadata.gz: bc9adf5a2aa075428b4fcf4824f73e642db324bed5cb9bf7d9e64e27b05b6ba4
4
+ data.tar.gz: 737d95c6221fc21aea6eb47785d1a2cd2825904880b8dfd620740c61a451d6cf
5
5
  SHA512:
6
- metadata.gz: 400c1b46c76250c1073488c1856967e6581b6cab2378e305208ca246ce312b4eac1066f2d9b1d1d8a2bc64bb1855f63650a516ea7af5f0aa102836d51e9545dc
7
- data.tar.gz: bf4a220e57f61852471ad93319576fdab39ed06936455b5c20565f7048dd0becd3b88f49d9567957ec1566a3552b50313acc4fa000180292c2ea3cfc25a67356
6
+ metadata.gz: a798171b54141af44ce5d1bbc88ae0d32282323a1924385f343424eec0e8b2cb49adf49c0073244e30e432cbbbc7d0c30ca559dc94999232b8f1d6a5e5aba92d
7
+ data.tar.gz: 65beaa5212f4df284b5add8e93b98c8693c1aed4fe5fbdf2f75c751016d60795e8ff84a9b173201f9d7439a3b6aaf20dd20b4ef7d33fc6b5e822b3f09f84f937
data/README.md CHANGED
@@ -15,6 +15,7 @@ It is an independent project, not affiliated with Hugging Face.
15
15
  - GGUF export of a merged model for llama.cpp, Ollama, and other local runtimes
16
16
  - Apple Silicon (MPS) as a first-class target, with CUDA and CPU auto-detected
17
17
  - Validation loss, per-epoch checkpoints, and resuming
18
+ - Training progress through a block, and its history in the adapter metadata
18
19
  - A CLI for training, merging, and generation, and `rpeft doctor` to check the Python environment
19
20
 
20
21
  ## The model behind the API
@@ -119,6 +120,28 @@ adapter.metadata.dig('training', 'eval_loss') # => 0.91
119
120
  `adapter.merge` returns a `RPEFT::Model` with `path` and `base_model`. `save` moves the artifact to the given path; a destination produced by a previous `save` is replaced,
120
121
  so scripts can be re-run, while any other existing path is refused.
121
122
 
123
+ ### Progress
124
+
125
+ A block given to `RPEFT::LoRA.train` is called as the run goes, with a `RPEFT::LoRA::Progress` for every logged training step (every 5 steps)
126
+ and for the evaluation at the end of each epoch:
127
+
128
+ ```ruby
129
+ adapter = RPEFT::LoRA.train(model: 'Qwen/Qwen2.5-Coder-0.5B', dataset: 'ruby_answers.jsonl') do |progress|
130
+ puts "step #{progress.step}/#{progress.total_steps} loss #{progress.loss}"
131
+ end
132
+ ```
133
+
134
+ A training step carries `loss` and `learning_rate`, an evaluation carries `eval_loss`, and both carry `step`, `total_steps`, and `epoch`; what a step lacks is `nil`.
135
+ An exception raised in the block ends the run, saves no adapter, and is raised from `train`. Ctrl-C ends a run the same way, at the next logged step.
136
+ `break` and `throw` cannot leave the block, which is called from Python: they end the run with `RPEFT::TrainingError`, so raise an exception to stop early.
137
+
138
+ The same steps are kept with or without a block, so runs can be compared afterwards:
139
+
140
+ ```ruby
141
+ adapter.metadata.dig('training', 'history')
142
+ # => [{"step" => 5, "epoch" => 0.5, "loss" => 1.81, "learning_rate" => 0.00019}, ...]
143
+ ```
144
+
122
145
  ### Generation
123
146
 
124
147
  `RPEFT::Model#generate` produces a completion for a prompt. It uses greedy decoding, so the output is deterministic for a given model and prompt.
@@ -212,6 +235,13 @@ Lines with `instruction`/`output` keys (and an optional `input`) are also accept
212
235
  {"instruction":"Explain what Array#map does","output":"It returns a new array with the block applied to each element."}
213
236
  ```
214
237
 
238
+ The prompt is the instruction under a `### Instruction:` heading, the input, if any, under `### Input:`, and a `### Response:` heading that the output follows.
239
+ A model trained this way expects the same prompt at inference, up to and including the line break after `### Response:`:
240
+
241
+ ```ruby
242
+ adapter.generate("### Instruction:\nExplain what Array#map does\n\n### Response:\n")
243
+ ```
244
+
215
245
  Chat transcripts are accepted as a `messages` array. These are rendered with the tokenizer's own chat template,
216
246
  so the conversation is formatted the way the model expects. Roles are limited to `system`, `user`, and `assistant`,
217
247
  the ones every chat template understands:
@@ -229,7 +259,9 @@ Examples whose answer does not fit within `max_length:` are skipped with a warni
229
259
  ```ruby
230
260
  RPEFT::LoRA.train(
231
261
  model: 'Qwen/Qwen2.5-Coder-0.5B',
232
- dataset: Article.published.map { |article| {text: article.body} }
262
+ dataset: CodingExample.where(language: 'Ruby').map { |example|
263
+ {instruction: example.prompt, output: example.completion}
264
+ }
233
265
  )
234
266
  ```
235
267
 
@@ -310,7 +342,7 @@ RPEFT.check # => a Hash describing Python, packages, and devices
310
342
 
311
343
  ```console
312
344
  $ rpeft doctor
313
- Ruby: 4.0.9 (rpeft 0.3.0)
345
+ Ruby: 4.0.9 (rpeft 0.4.0)
314
346
  Python: 3.12.13 (/path/to/.venv/bin/python)
315
347
  torch: OK 2.13.0
316
348
  transformers: OK 5.15.0
@@ -54,8 +54,45 @@ module RPEFT
54
54
  @mutex = Mutex.new
55
55
  end
56
56
 
57
- def train_lora(config)
58
- call(:train_lora, config, default_error: TrainingError)
57
+ # Yields each progress entry as a Hash. Whatever is raised while the block runs ends the run and is raised
58
+ # from here once Python is back: PyCall drops an exception raised while Python is calling into Ruby,
59
+ # and the training would carry on as if nothing had happened. That includes Interrupt, which Ruby raises
60
+ # wherever its code happens to be running, so the rescue covers everything Python calls, not the block alone.
61
+ def train_lora(config, &on_progress)
62
+ return call(:train_lora, config, default_error: TrainingError) unless on_progress
63
+
64
+ failure = nil
65
+ callback = lambda do |json|
66
+ next 'stop' if failure
67
+
68
+ left_early = true
69
+ on_progress.call(JSON.parse(json.to_s))
70
+ left_early = false
71
+ nil
72
+ rescue Exception => e # rubocop:disable Lint/RescueException
73
+ left_early = false
74
+ failure = e
75
+ 'stop'
76
+ ensure
77
+ # break and throw leave the block without raising, and PyCall drops them as it drops exceptions,
78
+ # so the run would go on to its end. They cannot be resumed once Python is back, so the run ends in an error;
79
+ # next cancels the jump and hands Python the answer that stops the run.
80
+ if left_early
81
+ failure ||= TrainingError.new(
82
+ 'the progress block was left with break or throw, which cannot pass through Python; ' \
83
+ 'raise an exception to end a run early'
84
+ )
85
+ next 'stop'
86
+ end
87
+ end
88
+ begin
89
+ result = call(:train_lora, config, callback, default_error: TrainingError)
90
+ rescue TrainingError
91
+ raise unless failure
92
+ end
93
+ raise failure if failure
94
+
95
+ result
59
96
  end
60
97
 
61
98
  def merge_lora(config)
@@ -76,10 +113,10 @@ module RPEFT
76
113
 
77
114
  private
78
115
 
79
- def call(name, config, default_error:)
116
+ def call(name, config, *extra, default_error:)
80
117
  facade = backend_module
81
118
  result = if config
82
- facade.public_send(name, JSON.generate(config))
119
+ facade.public_send(name, JSON.generate(config), *extra)
83
120
  else
84
121
  facade.public_send(name)
85
122
  end
data/lib/rpeft/backend.rb CHANGED
@@ -7,7 +7,8 @@ module RPEFT
7
7
  #
8
8
  # A backend implements four methods, each taking and returning plain Hashes with String keys:
9
9
  #
10
- # train_lora(config) -> Hash
10
+ # train_lora(config) -> Hash, yielding a progress Hash per logged step when given a block;
11
+ # what the block raises ends the run and is raised to the caller
11
12
  # merge_lora(config) -> Hash
12
13
  # generate(config) -> Hash
13
14
  # detect_device(config) -> Hash
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RPEFT
4
+ module LoRA
5
+ # One step of a training run, as the block given to LoRA.train sees it. A training step carries loss and learning_rate,
6
+ # an evaluation at the end of an epoch carries eval_loss, and whatever a step lacks is nil.
7
+ class Progress
8
+ attr_reader :step, :total_steps, :epoch, :loss, :eval_loss, :learning_rate
9
+
10
+ def initialize(entry)
11
+ @step = entry['step']
12
+ @total_steps = entry['total_steps']
13
+ @epoch = entry['epoch']
14
+ @loss = entry['loss']
15
+ @eval_loss = entry['eval_loss']
16
+ @learning_rate = entry['learning_rate']
17
+ freeze
18
+ end
19
+ end
20
+ end
21
+ end
data/lib/rpeft/lora.rb CHANGED
@@ -18,7 +18,8 @@ module RPEFT
18
18
  POSITIVE_NUMBER_OPTIONS = %i(alpha learning_rate).freeze
19
19
 
20
20
  class << self
21
- def train(model:, dataset:, eval_dataset: nil, rank: 8, alpha: 16, dropout: 0.05, target_modules: nil, epochs: 3, batch_size: 4, learning_rate: 2e-4, max_length: 512, train_on_prompt: false, output_dir: nil, device: :auto, checkpoints: false, resume: false)
21
+ # A block, if given, is called with a Progress for every logged training step and every evaluation.
22
+ def train(model:, dataset:, eval_dataset: nil, rank: 8, alpha: 16, dropout: 0.05, target_modules: nil, epochs: 3, batch_size: 4, learning_rate: 2e-4, max_length: 512, train_on_prompt: false, output_dir: nil, device: :auto, checkpoints: false, resume: false, &on_progress)
22
23
  options = {
23
24
  rank: rank,
24
25
  alpha: alpha,
@@ -42,9 +43,7 @@ module RPEFT
42
43
  resolved_device = Device.resolve(device)
43
44
 
44
45
  options[:eval_dataset] = evaluation_dataset
45
- result = RPEFT.backend.train_lora(
46
- request_payload(model, training_dataset, adapter_dir, resolved_device, options)
47
- )
46
+ result = run_backend(request_payload(model, training_dataset, adapter_dir, resolved_device, options), on_progress)
48
47
 
49
48
  build_adapter(
50
49
  adapter_dir: adapter_dir,
@@ -67,6 +66,14 @@ module RPEFT
67
66
 
68
67
  private
69
68
 
69
+ # The backend is given a block even when the caller gave none: an exception raised while the block runs ends the run,
70
+ # and Interrupt is such an exception, so Ctrl-C then ends a run at the next logged step rather than after the last one.
71
+ def run_backend(payload, on_progress)
72
+ RPEFT.backend.train_lora(payload) do |entry|
73
+ on_progress&.call(Progress.new(entry))
74
+ end
75
+ end
76
+
70
77
  def validate_options(options)
71
78
  POSITIVE_INTEGER_OPTIONS.each do |key|
72
79
  value = options[key]
@@ -212,7 +219,8 @@ module RPEFT
212
219
  'device' => result['device'] || device.to_s,
213
220
  'train_loss' => result['final_loss'],
214
221
  'eval_loss' => result['eval_loss'],
215
- 'duration_seconds' => result['train_runtime_seconds']
222
+ 'duration_seconds' => result['train_runtime_seconds'],
223
+ 'history' => result['history']
216
224
  }
217
225
  }
218
226
  end
data/lib/rpeft/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RPEFT
4
- VERSION = '0.3.0'
4
+ VERSION = '0.4.0'
5
5
  end
data/lib/rpeft.rb CHANGED
@@ -12,6 +12,7 @@ require_relative 'rpeft/model'
12
12
  require_relative 'rpeft/gguf'
13
13
  require_relative 'rpeft/lora'
14
14
  require_relative 'rpeft/lora/adapter'
15
+ require_relative 'rpeft/lora/progress'
15
16
  require_relative 'rpeft/backend'
16
17
  require_relative 'rpeft/diagnosis'
17
18
 
@@ -2,7 +2,8 @@
2
2
 
3
3
  Imported through PyCall; not a public API. Every facade function takes
4
4
  a JSON string and returns a JSON string, so only plain strings cross
5
- the PyCall boundary.
5
+ the PyCall boundary. The one callable that crosses, train_lora's
6
+ on_progress, is itself handed JSON strings only.
6
7
 
7
8
  This module must stay importable without torch installed: all heavy
8
9
  imports live inside function bodies, and diagnostics() reports what is
@@ -14,7 +15,7 @@ import math
14
15
  import os
15
16
  import sys
16
17
 
17
- __version__ = "0.3.0"
18
+ __version__ = "0.4.0"
18
19
 
19
20
 
20
21
  def _dumps(value):
@@ -53,12 +54,13 @@ def _repair_sys_executable():
53
54
  _repair_sys_executable()
54
55
 
55
56
 
56
- def train_lora(config_json):
57
+ def train_lora(config_json, on_progress=None):
58
+ """on_progress, if given, is called with a JSON string per logged step and may return "stop"."""
57
59
  from . import _training, _versions
58
60
 
59
61
  _versions.require_minimums()
60
62
 
61
- return _dumps(_training.train_lora(json.loads(config_json)))
63
+ return _dumps(_training.train_lora(json.loads(config_json), on_progress))
62
64
 
63
65
 
64
66
  def merge_lora(config_json):
@@ -3,10 +3,14 @@ import os
3
3
  import shutil
4
4
 
5
5
  from . import _data, _device, _models
6
- from ._errors import stage
6
+ from ._errors import BackendError, stage
7
7
 
8
+ # What on_progress returns to end the run early.
9
+ STOP = "stop"
10
+ HISTORY_KEYS = ("loss", "eval_loss", "learning_rate")
8
11
 
9
- def train_lora(config):
12
+
13
+ def train_lora(config, on_progress=None):
10
14
  lora = config.get("lora", {})
11
15
  resolved = _device.resolve_device(config.get("device"))
12
16
  device = resolved["device"]
@@ -30,9 +34,19 @@ def train_lora(config):
30
34
  with stage("training"):
31
35
  model, target_modules, param_counts = _apply_lora(model, lora)
32
36
  trainer = _build_trainer(model, tokenizer, dataset, eval_dataset, config, device, dtype)
37
+ progress = _progress_callback(on_progress) if on_progress is not None else None
38
+ if progress is not None:
39
+ trainer.add_callback(progress)
33
40
  resume = _resume_point(config)
34
41
  metrics = trainer.train(resume_from_checkpoint=resume).metrics
42
+ if progress is not None and progress.stopped:
43
+ # Nothing is saved: an adapter cut short is not the one that was asked for.
44
+ raise BackendError("training", "training was stopped by the progress callback")
35
45
  steps = trainer.state.global_step
46
+ # Taken before the evaluation below, which would log the last epoch's eval_loss a second time.
47
+ history = _history(trainer.state.log_history)
48
+ if progress is not None:
49
+ trainer.remove_callback(progress)
36
50
  if eval_dataset is not None:
37
51
  metrics = dict(metrics, **trainer.evaluate())
38
52
 
@@ -42,15 +56,55 @@ def train_lora(config):
42
56
  # just travel with it wherever the adapter directory is saved or shared.
43
57
  shutil.rmtree(_trainer_dir(output_dir), ignore_errors=True)
44
58
 
45
- return _result(
59
+ result = _result(
46
60
  config, device, dtype, target_modules, param_counts, metrics, steps, len(dataset), skipped, eval_skipped
47
61
  )
62
+ result["history"] = history
63
+ return result
48
64
  finally:
49
65
  model = None
50
66
  gc.collect()
51
67
  _device.empty_cache(device)
52
68
 
53
69
 
70
+ def _progress_callback(on_progress):
71
+ import json
72
+
73
+ from transformers import TrainerCallback
74
+
75
+ from . import _finite
76
+
77
+ class Progress(TrainerCallback):
78
+ stopped = False
79
+
80
+ def on_log(self, args, state, control, logs=None, **kwargs):
81
+ entry = _history_entry(dict(logs or {}, step=state.global_step))
82
+ if entry is None:
83
+ return
84
+
85
+ entry["total_steps"] = state.max_steps
86
+ # Only a JSON string crosses to the caller, as everywhere else at this boundary.
87
+ if on_progress(json.dumps(_finite(entry), allow_nan=False)) == STOP:
88
+ self.stopped = True
89
+ control.should_training_stop = True
90
+
91
+ return Progress()
92
+
93
+
94
+ def _history(log_history):
95
+ entries = (_history_entry(log) for log in log_history)
96
+ return [entry for entry in entries if entry is not None]
97
+
98
+
99
+ def _history_entry(log):
100
+ # The Trainer also logs a summary of the whole run, which holds neither a loss of a step nor an eval_loss.
101
+ values = {key: log[key] for key in HISTORY_KEYS if key in log}
102
+ if "loss" not in values and "eval_loss" not in values:
103
+ return None
104
+
105
+ return dict({"step": log.get("step"), "epoch": log.get("epoch")}, **values)
106
+
107
+
54
108
  def _load_dataset(config, tokenizer, name):
55
109
  return _data.load_tokenized_dataset(
56
110
  config[name + "_path"],
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.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Koichi ITO
@@ -73,6 +73,7 @@ files:
73
73
  - lib/rpeft/gguf.rb
74
74
  - lib/rpeft/lora.rb
75
75
  - lib/rpeft/lora/adapter.rb
76
+ - lib/rpeft/lora/progress.rb
76
77
  - lib/rpeft/messages.rb
77
78
  - lib/rpeft/model.rb
78
79
  - lib/rpeft/version.rb