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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 74527e43eb7c5d06b33fa44b6bc80fc57d7af6b1039248b0dd889f64cd6a7a5b
4
- data.tar.gz: 497bff43821c0b8b25059de10321ac93d61ca3eacf3428d40e2de8db37b86b37
3
+ metadata.gz: e72e65f59460cc4217035e8043cf25d6e2b1514638fd20589cdcf6949a9508ab
4
+ data.tar.gz: aeacf67c2210d3dc50508e21741badf255015cdcabcde184e8c51d1f83433b6f
5
5
  SHA512:
6
- metadata.gz: 5b1d932dc735db4961c1c6532139c750f423e1ca83404bca9f7a7e041a680e42037be253ec75198bcd5cef501da1174d6673ef1c8ec4a3c0f28de8d8b85be78e
7
- data.tar.gz: 6d0bca19e47a92cbc975ee0fb73c06f5e4d337b3d6164371f43fcbd2ab7b1065cdd0b1a4730068e895312435c6f2d6bc91a64b62ff45f87a54fa16ca2d3fe32a
6
+ metadata.gz: 400c1b46c76250c1073488c1856967e6581b6cab2378e305208ca246ce312b4eac1066f2d9b1d1d8a2bc64bb1855f63650a516ea7af5f0aa102836d51e9545dc
7
+ data.tar.gz: bf4a220e57f61852471ad93319576fdab39ed06936455b5c20565f7048dd0becd3b88f49d9567957ec1566a3552b50313acc4fa000180292c2ea3cfc25a67356
data/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # RPEFT
2
2
 
3
+ [![Gem Version](https://badge.fury.io/rb/rpeft.svg)](https://badge.fury.io/rb/rpeft)
4
+ [![CI](https://github.com/koic/rpeft/actions/workflows/main.yml/badge.svg)](https://github.com/koic/rpeft/actions/workflows/main.yml)
5
+
3
6
  RPEFT brings LoRA fine-tuning of large language models to Ruby. It provides an API and CLI that model the LoRA lifecycle,
4
7
  while the heavy lifting is done by the Python ecosystem (PyTorch, Hugging Face Transformers, PEFT, Datasets, Accelerate) through PyCall.
5
8
  It is an independent project, not affiliated with Hugging Face.
@@ -9,22 +12,23 @@ It is an independent project, not affiliated with Hugging Face.
9
12
  - LoRA fine-tuning from JSONL files or Ruby Enumerables, in plain text, instruction, and chat formats
10
13
  - Merging an adapter into its base model to produce a standalone model
11
14
  - Generation and chat with a merged model, a Hugging Face model id, or an adapter on top of its base model
15
+ - GGUF export of a merged model for llama.cpp, Ollama, and other local runtimes
12
16
  - Apple Silicon (MPS) as a first-class target, with CUDA and CPU auto-detected
13
17
  - Validation loss, per-epoch checkpoints, and resuming
14
18
  - A CLI for training, merging, and generation, and `rpeft doctor` to check the Python environment
15
19
 
16
20
  ## The model behind the API
17
21
 
18
- LoRA keeps the base model weights $W_0$ frozen and learns a low-rank update of rank $r$:
22
+ [LoRA](https://arxiv.org/abs/2106.09685) keeps the base model weights $W_0$ frozen and learns a low-rank update of rank $r$, scaled by $\alpha / r$:
19
23
 
20
24
  ```math
21
25
  \begin{aligned}
22
26
  W &= W_0 + \Delta W \\
23
- \Delta W &\approx BA
27
+ \Delta W &\approx \frac{\alpha}{r} BA
24
28
  \end{aligned}
25
29
  ```
26
30
 
27
- $A$ and $B$ are small matrices that together typically hold well under 1% of the model's parameters. Training produces them; merging adds $BA$ back into $W_0$.
31
+ $A$ and $B$ are small matrices that together typically hold well under 1% of the model's parameters. Training produces them; merging adds $\frac{\alpha}{r} BA$ back into $W_0$.
28
32
  The API is the same shape:
29
33
 
30
34
  ```mermaid
@@ -34,7 +38,7 @@ flowchart LR
34
38
 
35
39
  Merging is optional: an adapter can also generate on top of its base model as is.
36
40
 
37
- The [`rank:` option](#training-options) of `RPEFT::LoRA.train` is exactly the $r$ above.
41
+ The [`rank:` and `alpha:` options](#training-options) of `RPEFT::LoRA.train` are exactly the $r$ and $\alpha$ above.
38
42
 
39
43
  ## Requirements
40
44
 
@@ -96,7 +100,7 @@ adapter = RPEFT::LoRA.train(
96
100
  )
97
101
  adapter.save('./ruby-lora')
98
102
 
99
- model = adapter.merge # W = W0 + B A
103
+ model = adapter.merge # W = W0 + (alpha / r) B A
100
104
  model.save('./ruby-model')
101
105
  ```
102
106
 
@@ -176,21 +180,22 @@ The rule behind this also applies to choosing a dataset format: the prompt at in
176
180
 
177
181
  ### Training options
178
182
 
179
- | Option | Default | Meaning |
180
- | ----------------- | ------- | --------------------------------------------------------------------------------------- |
181
- | `rank:` | `8` | LoRA rank $r$, the rank of the low-rank update $BA$ |
182
- | `alpha:` | `16` | LoRA scaling factor (`lora_alpha` in PEFT) |
183
- | `dropout:` | `0.05` | LoRA dropout (`lora_dropout` in PEFT) |
184
- | `target_modules:` | `nil` | Modules to adapt, e.g. `%w(q_proj v_proj)`. `nil` uses PEFT's per-architecture defaults |
185
- | `epochs:` | `3` | Training epochs |
186
- | `batch_size:` | `4` | Per-device batch size |
187
- | `learning_rate:` | `2e-4` | Learning rate |
188
- | `max_length:` | `512` | Max token length per example |
189
- | `eval_dataset:` | `nil` | Held-out dataset, in the same format as `dataset:`. Enables per-epoch evaluation |
190
- | `checkpoints:` | `false` | Checkpoint every epoch so an interrupted run can resume; removed once training ends |
191
- | `resume:` | `false` | Resume from the last checkpoint in `output_dir`, which must be given explicitly |
192
- | `output_dir:` | `nil` | Adapter output directory: new, empty, or an earlier output. `nil` uses a temporary one |
193
- | `device:` | `:auto` | `:auto`, `:cuda`, `:mps`, or `:cpu` |
183
+ | Option | Default | Meaning |
184
+ | ------------------ | ------- | --------------------------------------------------------------------------------------- |
185
+ | `rank:` | `8` | LoRA rank $r$, the rank of the low-rank update $BA$ |
186
+ | `alpha:` | `16` | LoRA scaling factor $\alpha$ (`lora_alpha` in PEFT) |
187
+ | `dropout:` | `0.05` | LoRA dropout (`lora_dropout` in PEFT) |
188
+ | `target_modules:` | `nil` | Modules to adapt, e.g. `%w(q_proj v_proj)`. `nil` uses PEFT's per-architecture defaults |
189
+ | `epochs:` | `3` | Training epochs |
190
+ | `batch_size:` | `4` | Per-device batch size |
191
+ | `learning_rate:` | `2e-4` | Learning rate |
192
+ | `max_length:` | `512` | Max token length per example |
193
+ | `train_on_prompt:` | `false` | Compute the loss on prompts too, not only on answers (instruction and chat formats) |
194
+ | `eval_dataset:` | `nil` | Held-out dataset, in the same format as `dataset:`. Enables per-epoch evaluation |
195
+ | `checkpoints:` | `false` | Checkpoint every epoch so an interrupted run can resume; removed once training ends |
196
+ | `resume:` | `false` | Resume from the last checkpoint in `output_dir`, which must be given explicitly |
197
+ | `output_dir:` | `nil` | Adapter output directory: new, empty, or an earlier output. `nil` uses a temporary one |
198
+ | `device:` | `:auto` | `:auto`, `:cuda`, `:mps`, or `:cpu` |
194
199
 
195
200
  ### Dataset
196
201
 
@@ -215,6 +220,10 @@ the ones every chat template understands:
215
220
  {"messages":[{"role":"user","content":"How do I reverse an array?"},{"role":"assistant","content":"[1, 2, 3].reverse"}]}
216
221
  ```
217
222
 
223
+ In instruction and chat data, the prompt is read as context, but the loss is computed on the answers alone: the `output`, or every assistant turn after the first message with its end-of-turn marker.
224
+ A `text` line has no such boundary, so it is trained on as a whole. Pass `train_on_prompt: true` to compute the loss on every token instead.
225
+ Examples whose answer does not fit within `max_length:` are skipped with a warning, and the number skipped is recorded in the adapter metadata.
226
+
218
227
  `dataset:` also accepts any Enumerable of record Hashes in the same three shapes, so data built in Ruby needs no file of its own:
219
228
 
220
229
  ```ruby
@@ -240,6 +249,59 @@ Apple Silicon Macs (M1 and later) are a first-class target: small models such as
240
249
  Training uses float32 on MPS (half precision there is numerically fragile), bfloat16 on capable CUDA GPUs, and `PYTORCH_ENABLE_MPS_FALLBACK=1` is set automatically for
241
250
  operators MPS does not implement. Merging always runs on CPU, which is the memory-safest place for it.
242
251
 
252
+ ### Exporting to GGUF
253
+
254
+ A merged model can be written to a single GGUF file for llama.cpp, Ollama, and other local runtimes.
255
+ The conversion is done by llama.cpp's own `convert_hf_to_gguf.py`, which is not published as a package, so RPEFT needs a llama.cpp checkout:
256
+
257
+ ```console
258
+ $ git clone https://github.com/ggml-org/llama.cpp ~/src/llama.cpp
259
+ $ .venv/bin/pip install sentencepiece # or, with uv: uv pip install sentencepiece
260
+ ```
261
+
262
+ ```ruby
263
+ model = adapter.merge(output_dir: './ruby-model')
264
+ model.export_gguf('./ruby-model.gguf', llama_cpp: '~/src/llama.cpp') # => "/path/to/ruby-model.gguf"
265
+ ```
266
+
267
+ `llama_cpp:` defaults to the `LLAMA_CPP_DIR` environment variable. The converter runs in its own process with the Python RPEFT uses,
268
+ so the packages it needs beyond RPEFT's own go into the same environment. `sentencepiece` is one of them even for models without
269
+ a SentencePiece tokenizer, such as Qwen2.5, because the converter imports it before looking for one.
270
+
271
+ `quantize:` picks the type of the weights. `:q8_0` (the default), `:f16`, and `:bf16` are written by the converter directly.
272
+ `:q6_k`, `:q5_k_m`, and `:q4_k_m` are smaller and also need `llama-quantize`, found on `PATH` (`brew install llama.cpp`), in the checkout's `build/bin`,
273
+ or given as `llama_quantize:`. Small models lose more to quantization, which is why the default stays at 8 bits.
274
+
275
+ Export a model you merged yourself, from a directory no one else writes to while the export runs; an adapter is merged first.
276
+ An existing output file is never overwritten, and a failed export leaves nothing behind.
277
+
278
+ A GGUF file carries the model's chat template, and Ollama (checked with 0.33.1) wraps every prompt in it, even when a Modelfile gives a `TEMPLATE` of its own.
279
+ A model fine-tuned on plain text, like the example above, expects the prompt as it was in training, so export it without the chat template:
280
+
281
+ ```ruby
282
+ model.export_gguf('./ruby-model.gguf', chat_template: false, llama_cpp: '~/src/llama.cpp')
283
+ ```
284
+
285
+ This removes the default chat template, the one Ollama used in that check, and the list of named ones; templates stored under their own names, such as one for tool use, stay.
286
+ Leaving it out uses `gguf_new_metadata.py` from the same checkout and briefly needs room for one more copy of the file.
287
+ Keep the chat template for a model fine-tuned on chat-format data: Ollama then needs a Modelfile with the `FROM` line alone, and its chat answers as `#chat` does.
288
+
289
+ To run a file exported without its chat template in Ollama, point a Modelfile at it and give a template that passes the prompt through:
290
+
291
+ ```text
292
+ FROM ./ruby-model.gguf
293
+ TEMPLATE {{ .Prompt }}
294
+ ```
295
+
296
+ ```console
297
+ $ ollama create ruby-model -f Modelfile
298
+ $ ollama run ruby-model $'User: How do I find the minimum value in an array?\nAssistant:'
299
+ ```
300
+
301
+ The converter loads some tokenizers with `trust_remote_code=True`, so it runs offline with empty Hugging Face caches of its own, and a model directory is refused when it holds Python code,
302
+ `auto_map` in a JSON file, a link leading out of it or to a directory, a hard link, or a special file. Any of these could run code or carry another file, such as a credential, into the GGUF file.
303
+ The checks run before the converter starts, which is why the directory must not change during the export.
304
+
243
305
  ### Environment check
244
306
 
245
307
  ```ruby
@@ -248,7 +310,7 @@ RPEFT.check # => a Hash describing Python, packages, and devices
248
310
 
249
311
  ```console
250
312
  $ rpeft doctor
251
- Ruby: 4.0.6 (rpeft 0.1.0)
313
+ Ruby: 4.0.9 (rpeft 0.3.0)
252
314
  Python: 3.12.13 (/path/to/.venv/bin/python)
253
315
  torch: OK 2.13.0
254
316
  transformers: OK 5.15.0
@@ -256,18 +318,23 @@ peft: OK 0.20.0
256
318
  datasets: OK 5.0.1
257
319
  accelerate: OK 1.14.0
258
320
  Device: mps (CUDA: no, MPS: yes)
321
+ llama.cpp: OK /Users/you/src/llama.cpp
322
+ Quantizer: OK /opt/homebrew/bin/llama-quantize
259
323
  Status: OK
260
324
  ```
261
325
 
326
+ The llama.cpp lines are optional, for GGUF export only, and never affect the status.
327
+
262
328
  ### Errors
263
329
 
264
330
  Python exceptions never surface raw. They are translated into `RPEFT::DependencyError`, `RPEFT::ModelLoadError`, `RPEFT::DatasetError`, `RPEFT::TrainingError`,
265
331
  `RPEFT::MergeError`, or `RPEFT::GenerationError`, and the original Python error (with its traceback) stays reachable via `error.cause`.
332
+ A failing llama.cpp tool during GGUF export raises `RPEFT::ExportError` with the end of the tool's output.
266
333
  Invalid arguments are rejected in Ruby with `RPEFT::ConfigurationError` before the backend is called.
267
334
 
268
335
  ## CLI
269
336
 
270
- The CLI covers the core of the lifecycle: training, merging, and generation from a prompt.
337
+ The CLI covers the core of the lifecycle: training, merging, generation from a prompt, and GGUF export.
271
338
  Validation datasets, checkpoints, and chat are available from the Ruby API only.
272
339
 
273
340
  ```console
@@ -303,6 +370,16 @@ $ rpeft generate \
303
370
  --prompt $'User: How do I find the minimum value in an array?\nAssistant:'
304
371
  ```
305
372
 
373
+ A merged model is exported to GGUF with `rpeft export gguf`, which takes the same choices as `export_gguf`:
374
+
375
+ ```console
376
+ $ rpeft export gguf \
377
+ --model ruby-model \
378
+ --output ruby-model.gguf \
379
+ --no-chat-template \
380
+ --llama-cpp ~/src/llama.cpp
381
+ ```
382
+
306
383
  `rpeft doctor` and `rpeft version` are also available.
307
384
 
308
385
  ## Examples
@@ -28,6 +28,7 @@ module RPEFT
28
28
  else
29
29
  line 'Backend', "NG #{backend['error']}"
30
30
  end
31
+ render_gguf(report['gguf'])
31
32
 
32
33
  # Uppercase for consistency with the OK/MISSING library markers;
33
34
  # the check API itself keeps the machine-readable lowercase value.
@@ -35,9 +36,11 @@ module RPEFT
35
36
  render_hint(report)
36
37
  end
37
38
 
39
+ # Values come from the environment, such as LLAMA_CPP_DIR and the directories on PATH, which may hold
40
+ # escape sequences a terminal would act on.
38
41
  def line(label, value)
39
42
  padded = "#{label}:".ljust(14)
40
- @out.puts "#{padded}#{value}"
43
+ @out.puts "#{padded}#{printable(value)}"
41
44
  end
42
45
 
43
46
  def render_python(python)
@@ -65,6 +68,20 @@ module RPEFT
65
68
  line 'Device', "#{device['recommended']} (CUDA: #{cuda}, MPS: #{mps})"
66
69
  end
67
70
 
71
+ def render_gguf(gguf)
72
+ gguf ||= {}
73
+
74
+ if gguf['converter']
75
+ line 'llama.cpp', "OK #{gguf['llama_cpp_dir']}"
76
+ elsif gguf['llama_cpp_dir']
77
+ line 'llama.cpp', "NG no #{GGUF::CONVERTER} in #{gguf['llama_cpp_dir']} (LLAMA_CPP_DIR)"
78
+ else
79
+ line 'llama.cpp', 'not configured (optional, set LLAMA_CPP_DIR for GGUF export)'
80
+ end
81
+
82
+ line 'Quantizer', gguf['quantizer'] ? "OK #{gguf['quantizer']}" : "no #{GGUF::QUANTIZER} (optional, for q6_k, q5_k_m, and q4_k_m)"
83
+ end
84
+
68
85
  def render_hint(report)
69
86
  return unless report['status'] == 'degraded'
70
87
 
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RPEFT
4
+ module CLI
5
+ # @api private
6
+ class ExportGGUF < Command
7
+ REQUIRED_OPTIONS = %i(model output).freeze
8
+
9
+ private
10
+
11
+ def option_parser(options)
12
+ OptionParser.new do |o|
13
+ o.banner = 'Usage: rpeft export gguf --model DIR --output FILE [options]'
14
+ o.on('--model DIR', 'Model directory to export, such as a merged model') do |v|
15
+ options[:model] = v
16
+ end
17
+ o.on('--output FILE', 'GGUF file to write') do |v|
18
+ options[:output] = v
19
+ end
20
+ o.on('--quantize TYPE', "#{GGUF::TYPES.join(', ')}, in any case (default: q8_0)") do |v|
21
+ type = v.downcase.to_sym
22
+ raise OptionParser::InvalidArgument, v unless GGUF::TYPES.include?(type)
23
+
24
+ options[:quantize] = type
25
+ end
26
+ o.on('--no-chat-template', 'Leave out the chat template, for a model fine-tuned on plain text') do
27
+ options[:chat_template] = false
28
+ end
29
+ o.on('--llama-cpp DIR', 'llama.cpp checkout holding convert_hf_to_gguf.py (default: $LLAMA_CPP_DIR)') do |v|
30
+ options[:llama_cpp] = v
31
+ end
32
+ o.on('--llama-quantize PATH', 'llama-quantize executable for q6_k, q5_k_m, and q4_k_m (default: from PATH)') do |v|
33
+ options[:llama_quantize] = v
34
+ end
35
+ end
36
+ end
37
+
38
+ def required_options
39
+ REQUIRED_OPTIONS
40
+ end
41
+
42
+ def execute(options)
43
+ export_options = options.slice(:quantize, :chat_template, :llama_cpp, :llama_quantize)
44
+ path = Model.new(path: options[:model]).export_gguf(options[:output], **export_options)
45
+
46
+ @out.puts "GGUF saved to #{printable(path)}"
47
+ 0
48
+ end
49
+ end
50
+ end
51
+ end
@@ -4,8 +4,9 @@ module RPEFT
4
4
  module CLI
5
5
  # @api private
6
6
  class LoRATrain < Command
7
- PASSTHROUGH_OPTIONS = %i(rank alpha dropout target_modules epochs batch_size
8
- learning_rate max_length device).freeze
7
+ PASSTHROUGH_OPTIONS = %i(
8
+ rank alpha dropout target_modules epochs batch_size learning_rate max_length train_on_prompt device
9
+ ).freeze
9
10
  REQUIRED_OPTIONS = %i(model dataset output).freeze
10
11
  DEVICES = %w(auto cuda mps cpu).freeze
11
12
 
@@ -26,7 +27,7 @@ module RPEFT
26
27
  o.on('--rank N', Integer, 'LoRA rank r (default: 8)') do |v|
27
28
  options[:rank] = v
28
29
  end
29
- o.on('--alpha N', Float, 'LoRA alpha (default: 16)') do |v|
30
+ o.on('--alpha N', Float, 'LoRA scaling factor alpha (default: 16)') do |v|
30
31
  options[:alpha] = v
31
32
  end
32
33
  o.on('--dropout F', Float, 'LoRA dropout (default: 0.05)') do |v|
@@ -48,6 +49,9 @@ module RPEFT
48
49
  o.on('--max-length N', Integer, 'Max token length (default: 512)') do |v|
49
50
  options[:max_length] = v
50
51
  end
52
+ o.on('--train-on-prompt', 'Also train on the prompt of instruction and chat examples') do
53
+ options[:train_on_prompt] = true
54
+ end
51
55
  o.on('--device DEVICE', DEVICES,
52
56
  'auto, cuda, mps, or cpu (default: auto)') { |v| options[:device] = v.to_sym }
53
57
  end
data/lib/rpeft/cli.rb CHANGED
@@ -6,6 +6,7 @@ require_relative 'cli/lora_train'
6
6
  require_relative 'cli/lora_merge'
7
7
  require_relative 'cli/generate'
8
8
  require_relative 'cli/doctor'
9
+ require_relative 'cli/export_gguf'
9
10
 
10
11
  module RPEFT
11
12
  # Command line interface. Commands go through the public Ruby API only,
@@ -18,6 +19,7 @@ module RPEFT
18
19
  lora train Fine-tune a base model with LoRA
19
20
  lora merge Merge a LoRA adapter into its base model
20
21
  generate Generate text from a base or fine-tuned model
22
+ export gguf Export a model to a GGUF file for llama.cpp and Ollama
21
23
  doctor Diagnose the Python environment
22
24
  version Print the RPEFT version
23
25
  help Show this message
@@ -33,11 +35,19 @@ module RPEFT
33
35
  merge Merge a LoRA adapter into its base model
34
36
  USAGE
35
37
 
38
+ EXPORT_USAGE = <<~USAGE
39
+ Usage: rpeft export <format> [options]
40
+
41
+ Formats:
42
+ gguf Export a model to a GGUF file for llama.cpp and Ollama
43
+ USAGE
44
+
36
45
  class << self
37
46
  def run(argv, out: $stdout, err: $stderr)
38
47
  command, *rest = argv
39
48
  case command
40
49
  when 'lora' then run_lora(rest, out: out, err: err)
50
+ when 'export' then run_export(rest, out: out, err: err)
41
51
  when 'generate' then Generate.run(rest, out: out, err: err)
42
52
  when 'doctor' then Doctor.run(rest, out: out, err: err)
43
53
  when 'version', '--version', '-v'
@@ -72,6 +82,21 @@ module RPEFT
72
82
  2
73
83
  end
74
84
  end
85
+
86
+ def run_export(argv, out:, err:)
87
+ format, *rest = argv
88
+
89
+ case format
90
+ when 'gguf' then ExportGGUF.run(rest, out: out, err: err)
91
+ when nil, 'help', '--help', '-h'
92
+ out.puts EXPORT_USAGE
93
+ 0
94
+ else
95
+ err.puts "rpeft: unknown export format #{format.inspect}"
96
+ err.puts EXPORT_USAGE
97
+ 2
98
+ end
99
+ end
75
100
  end
76
101
  end
77
102
  end
data/lib/rpeft/dataset.rb CHANGED
@@ -10,9 +10,11 @@ module RPEFT
10
10
  #
11
11
  # Three JSONL line formats are accepted and detected from the first line: `{"text": ...}` is
12
12
  # passed through as is, `{"instruction": ..., "input": ..., "output": ...}` is rendered into
13
- # a text prompt, and `{"messages": [{"role": ..., "content": ...}, ...]}` is passed through
13
+ # a prompt and its completion, and `{"messages": [{"role": ..., "content": ...}, ...]}` is passed through
14
14
  # for the backend to render with the tokenizer's chat template.
15
15
  class Dataset
16
+ BACKEND_FORMATS = {text: 'text', instruction: 'completion', messages: 'messages'}.freeze
17
+
16
18
  def self.coerce(value)
17
19
  return value if value.is_a?(Dataset)
18
20
  return from_records(value) if value.is_a?(Enumerable)
@@ -63,10 +65,14 @@ module RPEFT
63
65
  @temporary_dirs.clear
64
66
  end
65
67
 
66
- # The format the backend sees. Instruction datasets are normalized to text here,
67
- # so only text and messages ever cross the boundary.
68
+ # The format the backend sees. Instruction datasets are normalized to prompt and completion pairs here,
69
+ # which keeps the boundary the backend needs to train on the completion alone.
68
70
  def backend_format
69
- format == :messages ? 'messages' : 'text'
71
+ BACKEND_FORMATS.fetch(format)
72
+ end
73
+
74
+ def messages?
75
+ format == :messages
70
76
  end
71
77
 
72
78
  private
@@ -112,8 +118,8 @@ module RPEFT
112
118
  raise DatasetError, "dataset is not JSONL (#{e.message}): #{path}"
113
119
  end
114
120
 
115
- # Rewrites a non-text dataset into text-format JSONL in
116
- # a temporary directory, so the backend only ever sees one format.
121
+ # Rewrites an instruction dataset into prompt and completion JSONL in a temporary directory,
122
+ # so the backend needs no knowledge of the instruction template.
117
123
  def normalize(source_path)
118
124
  dir = Dir.mktmpdir('rpeft-dataset-')
119
125
  @temporary_dirs << dir
@@ -124,7 +130,9 @@ module RPEFT
124
130
  next if line.strip.empty?
125
131
 
126
132
  record = parse_line(line, source_path)
127
- out.puts JSON.generate('text' => render_instruction(record, lineno, source_path))
133
+ prompt, completion = render_instruction(record, lineno, source_path)
134
+
135
+ out.puts JSON.generate('prompt' => prompt, 'completion' => completion)
128
136
  end
129
137
  end
130
138
 
@@ -142,10 +150,11 @@ module RPEFT
142
150
  end
143
151
 
144
152
  input = record['input']
145
- text = "### Instruction:\n#{instruction}\n"
146
- text << "\n### Input:\n#{input}\n" if input && !input.to_s.empty?
147
- text << "\n### Response:\n#{output}"
148
- text
153
+ prompt = "### Instruction:\n#{instruction}\n"
154
+ prompt << "\n### Input:\n#{input}\n" if input && !input.to_s.empty?
155
+ prompt << "\n### Response:\n"
156
+
157
+ [prompt, output]
149
158
  end
150
159
  end
151
160
  end
@@ -12,7 +12,8 @@ module RPEFT
12
12
  end
13
13
 
14
14
  def report
15
- base = {'ruby' => {'version' => RUBY_VERSION, 'rpeft' => VERSION}}
15
+ # The llama.cpp tools are optional, for GGUF export only, so they never affect the status.
16
+ base = {'ruby' => {'version' => RUBY_VERSION, 'rpeft' => VERSION}, 'gguf' => GGUF.tools}
16
17
  begin
17
18
  diagnostics = @backend.diagnostics
18
19
  rescue Error => e
data/lib/rpeft/errors.rb CHANGED
@@ -23,4 +23,7 @@ module RPEFT
23
23
 
24
24
  # Text generation failed.
25
25
  class GenerationError < Error; end
26
+
27
+ # Exporting a model to another format, such as GGUF, failed in the external tool doing the conversion.
28
+ class ExportError < Error; end
26
29
  end