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 +4 -4
- data/README.md +99 -22
- data/lib/rpeft/cli/doctor.rb +18 -1
- data/lib/rpeft/cli/export_gguf.rb +51 -0
- data/lib/rpeft/cli/lora_train.rb +7 -3
- data/lib/rpeft/cli.rb +25 -0
- data/lib/rpeft/dataset.rb +20 -11
- data/lib/rpeft/diagnosis.rb +2 -1
- data/lib/rpeft/errors.rb +3 -0
- data/lib/rpeft/gguf.rb +353 -0
- data/lib/rpeft/lora/adapter.rb +2 -2
- data/lib/rpeft/lora.rb +24 -7
- data/lib/rpeft/model.rb +9 -0
- data/lib/rpeft/version.rb +1 -1
- data/lib/rpeft.rb +1 -0
- data/python/rpeft_backend/__init__.py +1 -1
- data/python/rpeft_backend/_chat.py +35 -2
- data/python/rpeft_backend/_data.py +104 -26
- data/python/rpeft_backend/_training.py +35 -24
- metadata +4 -2
data/lib/rpeft/gguf.rb
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'find'
|
|
4
|
+
require 'json'
|
|
5
|
+
require 'open3'
|
|
6
|
+
require 'tmpdir'
|
|
7
|
+
|
|
8
|
+
module RPEFT
|
|
9
|
+
# Exports a merged model directory to a single GGUF file for llama.cpp, Ollama, and other local runtimes.
|
|
10
|
+
#
|
|
11
|
+
# The conversion is left to llama.cpp's own tools, which know every architecture and tokenizer GGUF supports:
|
|
12
|
+
# its `convert_hf_to_gguf.py` writes 16-bit or Q8_0 files, and `llama-quantize` turns a 16-bit file into
|
|
13
|
+
# the K-quant types. RPEFT checks the input, runs the tools, and cleans up after them.
|
|
14
|
+
module GGUF
|
|
15
|
+
CONVERTER = 'convert_hf_to_gguf.py'
|
|
16
|
+
QUANTIZER = 'llama-quantize'
|
|
17
|
+
METADATA_EDITOR = File.join('gguf-py', 'gguf', 'scripts', 'gguf_new_metadata.py')
|
|
18
|
+
CHAT_TEMPLATE_KEY = 'tokenizer.chat_template'
|
|
19
|
+
# The list of a model's named templates, such as one for tool use. The templates themselves sit under keys
|
|
20
|
+
# holding their names, which only a reader of the file would know, so they stay; the default one is what Ollama was seen to use.
|
|
21
|
+
CHAT_TEMPLATE_NAMES_KEY = 'tokenizer.chat_templates'
|
|
22
|
+
MAGIC = 'GGUF'
|
|
23
|
+
|
|
24
|
+
# Types the converter writes directly, by its --outtype name.
|
|
25
|
+
CONVERTED = {f16: 'f16', bf16: 'bf16', q8_0: 'q8_0'}.freeze
|
|
26
|
+
# Types that need a 16-bit file run through llama-quantize, by its type name.
|
|
27
|
+
QUANTIZED = {q6_k: 'Q6_K', q5_k_m: 'Q5_K_M', q4_k_m: 'Q4_K_M'}.freeze
|
|
28
|
+
TYPES = [*CONVERTED.keys, *QUANTIZED.keys].freeze
|
|
29
|
+
MAX_JSON_BYTES = 256 * 1024 * 1024
|
|
30
|
+
|
|
31
|
+
# Runs a command given as an argument list, never through a shell, with extra environment variables,
|
|
32
|
+
# and returns its combined output and whether it succeeded. Replaced in tests so that no external tool runs.
|
|
33
|
+
DEFAULT_RUNNER = lambda do |argv, env|
|
|
34
|
+
output, status = Open3.capture2e(env, *argv)
|
|
35
|
+
|
|
36
|
+
[output, status.success?]
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
class << self
|
|
40
|
+
attr_writer :runner
|
|
41
|
+
|
|
42
|
+
def runner
|
|
43
|
+
@runner || DEFAULT_RUNNER
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def export(model_dir, output, quantize: :q8_0, chat_template: true, llama_cpp: nil, llama_quantize: nil)
|
|
47
|
+
type = quantize_type(quantize)
|
|
48
|
+
raise ConfigurationError, "chat_template must be true or false, got #{chat_template.inspect}" unless [true, false].include?(chat_template)
|
|
49
|
+
|
|
50
|
+
model_dir = model_directory(model_dir)
|
|
51
|
+
output = output_path(output)
|
|
52
|
+
llama_cpp_dir = llama_cpp_directory(llama_cpp)
|
|
53
|
+
converter = converter_path(llama_cpp_dir)
|
|
54
|
+
quantizer = quantizer_path(llama_quantize, llama_cpp_dir) if QUANTIZED.key?(type)
|
|
55
|
+
editor = metadata_editor_path(llama_cpp_dir) unless chat_template
|
|
56
|
+
|
|
57
|
+
# The tools write into a directory of their own next to the output, under fixed names: the converter
|
|
58
|
+
# expands placeholders such as {ftype} in the name it is given, so it never sees the caller's name.
|
|
59
|
+
# Only a verified file reaches the output, and everything else goes with the directory, including the bf16
|
|
60
|
+
# intermediate of the K-quant types, which is as large as the model and so belongs on the output's disk.
|
|
61
|
+
Dir.mktmpdir('.rpeft-gguf-', File.dirname(output)) do |dir|
|
|
62
|
+
staged = File.join(dir, 'model.gguf')
|
|
63
|
+
env = converter_env(dir)
|
|
64
|
+
|
|
65
|
+
if quantizer
|
|
66
|
+
intermediate = File.join(dir, 'model-bf16.gguf')
|
|
67
|
+
convert(model_dir, intermediate, 'bf16', converter, env)
|
|
68
|
+
run([quantizer, intermediate, staged, QUANTIZED.fetch(type)], QUANTIZER)
|
|
69
|
+
else
|
|
70
|
+
convert(model_dir, staged, CONVERTED.fetch(type), converter, env)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
verify(staged, quantizer ? QUANTIZER : CONVERTER)
|
|
74
|
+
staged = remove_chat_template(staged, editor, env) if editor
|
|
75
|
+
|
|
76
|
+
publish(staged, output)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
output
|
|
80
|
+
rescue SystemCallError => e
|
|
81
|
+
raise ExportError, "GGUF export to #{output} failed: #{e.message}"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# The llama.cpp tools as RPEFT would find them now, for `rpeft doctor`. Never raises.
|
|
85
|
+
def tools(env: ENV)
|
|
86
|
+
configured = env.fetch('LLAMA_CPP_DIR', '').to_s
|
|
87
|
+
dir = configured.empty? ? nil : expand(configured) || configured
|
|
88
|
+
converter = dir && File.join(dir, CONVERTER)
|
|
89
|
+
|
|
90
|
+
{
|
|
91
|
+
'llama_cpp_dir' => dir,
|
|
92
|
+
'converter' => converter && File.file?(converter) ? converter : nil,
|
|
93
|
+
'quantizer' => find_quantizer(dir, env)
|
|
94
|
+
}
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
private
|
|
98
|
+
|
|
99
|
+
def quantize_type(value)
|
|
100
|
+
type = value.to_s.downcase.to_sym if value.is_a?(String) || value.is_a?(Symbol)
|
|
101
|
+
return type if TYPES.include?(type)
|
|
102
|
+
|
|
103
|
+
raise ConfigurationError, "quantize must be one of #{TYPES.join(', ')}, got #{value.inspect}"
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def model_directory(value)
|
|
107
|
+
dir = expanded_path(value, 'model')
|
|
108
|
+
|
|
109
|
+
unless File.directory?(dir)
|
|
110
|
+
raise ConfigurationError, "GGUF export needs a local model directory, got #{dir.inspect}; save a Hub model or merge an adapter into a directory first"
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
if File.file?(File.join(dir, 'adapter_config.json'))
|
|
114
|
+
raise ConfigurationError, "#{dir} is a LoRA adapter; merge it into its base model before exporting to GGUF"
|
|
115
|
+
end
|
|
116
|
+
raise ConfigurationError, "#{dir} has no config.json, so it is not a Transformers model directory" unless File.file?(File.join(dir, 'config.json'))
|
|
117
|
+
|
|
118
|
+
refuse_custom_code(dir)
|
|
119
|
+
|
|
120
|
+
dir
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# A model RPEFT merged ships no custom code, so a directory that does is refused rather than trusted:
|
|
124
|
+
# Python files, and auto_map in any JSON file, since a config can name further config files
|
|
125
|
+
# (configuration_files) that Transformers reads instead. Extensions are compared in any case, as a file
|
|
126
|
+
# system such as macOS's default one finds configuration_x.PY when Transformers asks for
|
|
127
|
+
# configuration_x.py. Find covers hidden directories too and does not follow links.
|
|
128
|
+
#
|
|
129
|
+
# The check runs once, and the converter reads the directory again later, so a directory someone else can
|
|
130
|
+
# write to in between is not covered. Checking a private copy instead would cost a full copy of the model,
|
|
131
|
+
# for a directory that is normally a model the user merged; the README asks for such a directory instead.
|
|
132
|
+
def refuse_custom_code(dir)
|
|
133
|
+
# The model directory itself may be reached through a link, which Find would not enter.
|
|
134
|
+
root = File.realpath(dir)
|
|
135
|
+
|
|
136
|
+
Find.find(root) do |path|
|
|
137
|
+
next if path == root
|
|
138
|
+
|
|
139
|
+
name = path.delete_prefix("#{root}/")
|
|
140
|
+
refuse_entry(dir, root, name, path)
|
|
141
|
+
extension = File.extname(path).downcase
|
|
142
|
+
raise ConfigurationError, "#{dir} contains Python code (#{name}), which the GGUF converter could run" if extension == '.py'
|
|
143
|
+
|
|
144
|
+
refuse_auto_map(dir, name, path) if extension == '.json' && File.file?(path)
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# The converter reads whatever a name in the directory leads to and writes some of it, such as the chat
|
|
149
|
+
# template, into the GGUF file. A link leading out of the directory, or a hard link, could thus carry
|
|
150
|
+
# another file, such as a credential, into a GGUF file that is then published, and a special file such
|
|
151
|
+
# as a FIFO could stall the converter. A link to a directory is refused because Find does not enter it.
|
|
152
|
+
def refuse_entry(dir, root, name, path)
|
|
153
|
+
stat = File.lstat(path)
|
|
154
|
+
if stat.symlink?
|
|
155
|
+
refuse_link(dir, root, name, path)
|
|
156
|
+
elsif stat.file?
|
|
157
|
+
raise ConfigurationError, "#{dir} holds #{name}, a hard link that may share another file's contents" if stat.nlink > 1
|
|
158
|
+
elsif !stat.directory?
|
|
159
|
+
raise ConfigurationError, "#{dir} holds #{name}, which is not a regular file"
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def refuse_link(dir, root, name, path)
|
|
164
|
+
target = File.realpath(path)
|
|
165
|
+
|
|
166
|
+
raise ConfigurationError, "#{dir} holds #{name}, a link leading outside the directory" unless target.start_with?("#{root}/")
|
|
167
|
+
raise ConfigurationError, "#{dir} holds #{name}, a link to a directory, which RPEFT cannot check" if File.directory?(target)
|
|
168
|
+
raise ConfigurationError, "#{dir} holds #{name}, a link to something other than a regular file" unless File.file?(target)
|
|
169
|
+
rescue Errno::ENOENT, Errno::ELOOP
|
|
170
|
+
raise ConfigurationError, "#{dir} holds #{name}, a link that leads nowhere"
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# Every JSON file is parsed rather than searched for the text auto_map, which a key can spell with
|
|
174
|
+
# a Unicode escape for any of its letters; a multi-megabyte tokenizer.json takes tens of milliseconds.
|
|
175
|
+
# NaN is allowed, as Python's json, which reads the configs, allows it.
|
|
176
|
+
def refuse_auto_map(dir, name, path)
|
|
177
|
+
# Configs and tokenizers run to tens of megabytes at most; a larger file would only be read into memory.
|
|
178
|
+
if File.size(path) > MAX_JSON_BYTES
|
|
179
|
+
raise ConfigurationError, "#{dir} holds #{name}, a JSON file larger than #{MAX_JSON_BYTES / 1024 / 1024} MB"
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
config = JSON.parse(File.read(path), allow_nan: true)
|
|
183
|
+
return unless config.is_a?(Hash) && config.key?('auto_map')
|
|
184
|
+
|
|
185
|
+
raise ConfigurationError, "#{dir} maps classes to custom code (auto_map in #{name}), which the GGUF converter could run"
|
|
186
|
+
rescue JSON::ParserError => e
|
|
187
|
+
raise ConfigurationError, "#{dir} holds #{name}, which is not valid JSON: #{e.message}"
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def output_path(value)
|
|
191
|
+
path = expanded_path(value, 'output')
|
|
192
|
+
|
|
193
|
+
# File.exist? is false for a link whose target is missing, which the converter would write through.
|
|
194
|
+
if File.exist?(path) || File.symlink?(path)
|
|
195
|
+
raise ConfigurationError, "output #{path} already exists; remove it or choose another path"
|
|
196
|
+
end
|
|
197
|
+
raise ConfigurationError, "output directory #{File.dirname(path)} does not exist" unless File.directory?(File.dirname(path))
|
|
198
|
+
|
|
199
|
+
path
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def llama_cpp_directory(llama_cpp)
|
|
203
|
+
dir = llama_cpp ? Arguments.path(llama_cpp, 'llama_cpp') : ENV.fetch('LLAMA_CPP_DIR', '')
|
|
204
|
+
|
|
205
|
+
if dir.empty?
|
|
206
|
+
raise DependencyError, 'GGUF export needs a llama.cpp checkout for its converter: clone ' \
|
|
207
|
+
'https://github.com/ggml-org/llama.cpp and pass llama_cpp: (--llama-cpp) or set LLAMA_CPP_DIR'
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
expand(dir) || raise(ConfigurationError, "llama_cpp #{dir.inspect} cannot be expanded to a path")
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def converter_path(llama_cpp_dir)
|
|
214
|
+
converter = File.join(llama_cpp_dir, CONVERTER)
|
|
215
|
+
raise DependencyError, "#{CONVERTER} not found in #{llama_cpp_dir}; is it a llama.cpp checkout?" unless File.file?(converter)
|
|
216
|
+
|
|
217
|
+
converter
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def metadata_editor_path(llama_cpp_dir)
|
|
221
|
+
editor = File.join(llama_cpp_dir, METADATA_EDITOR)
|
|
222
|
+
raise DependencyError, "#{METADATA_EDITOR} not found in #{llama_cpp_dir}, needed for chat_template: false" unless File.file?(editor)
|
|
223
|
+
|
|
224
|
+
editor
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def quantizer_path(llama_quantize, llama_cpp_dir)
|
|
228
|
+
if llama_quantize
|
|
229
|
+
path = expanded_path(llama_quantize, 'llama_quantize')
|
|
230
|
+
return path if File.file?(path) && File.executable?(path)
|
|
231
|
+
|
|
232
|
+
raise DependencyError, "#{path} is not an executable #{QUANTIZER}"
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
found = find_quantizer(llama_cpp_dir, ENV)
|
|
236
|
+
return found if found
|
|
237
|
+
|
|
238
|
+
raise DependencyError, "#{QUANTIZER} not found for the K-quant types; install llama.cpp (e.g. `brew install llama.cpp`), " \
|
|
239
|
+
'build it in the llama.cpp checkout, or pass llama_quantize: (--llama-quantize)'
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def find_quantizer(llama_cpp_dir, env)
|
|
243
|
+
candidates = env.fetch('PATH', '').split(File::PATH_SEPARATOR).reject(&:empty?).map { |dir| File.join(dir, QUANTIZER) }
|
|
244
|
+
candidates << File.join(llama_cpp_dir, 'build', 'bin', QUANTIZER) if llama_cpp_dir
|
|
245
|
+
|
|
246
|
+
candidates.find { |path| File.file?(path) && File.executable?(path) }
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
def expanded_path(value, name)
|
|
250
|
+
path = Arguments.path(value, name)
|
|
251
|
+
|
|
252
|
+
expand(path) || raise(ConfigurationError, "#{name} #{path.inspect} cannot be expanded to a path")
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
# File.expand_path raises for a ~user that does not exist; nil stands for that here.
|
|
256
|
+
def expand(path)
|
|
257
|
+
File.expand_path(path)
|
|
258
|
+
rescue ArgumentError
|
|
259
|
+
nil
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
def convert(model_dir, output, outtype, converter, env)
|
|
263
|
+
run([python, converter, model_dir, '--outfile', output, '--outtype', outtype], CONVERTER, env)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# Ollama (checked with 0.33.1) wraps every prompt in the chat template a GGUF file carries, even when
|
|
267
|
+
# a Modelfile gives a TEMPLATE of its own. A model fine-tuned on plain text expects its prompt as it was in
|
|
268
|
+
# training, so for such a model the template is left out. The editor writes a whole new file, skips keys
|
|
269
|
+
# the file does not have, and with --force skips its confirmation prompt.
|
|
270
|
+
def remove_chat_template(staged, editor, env)
|
|
271
|
+
edited = File.join(File.dirname(staged), 'model-no-chat-template.gguf')
|
|
272
|
+
argv = [
|
|
273
|
+
python, editor, '--remove-metadata', CHAT_TEMPLATE_KEY, '--remove-metadata', CHAT_TEMPLATE_NAMES_KEY, '--force', staged, edited
|
|
274
|
+
]
|
|
275
|
+
|
|
276
|
+
run(argv, File.basename(editor), env)
|
|
277
|
+
verify(edited, File.basename(editor))
|
|
278
|
+
|
|
279
|
+
edited
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
# The converter loads some tokenizers with trust_remote_code=True. Besides the model directory, checked
|
|
283
|
+
# by refuse_custom_code, that code could come from the Hugging Face Hub, which offline mode keeps out,
|
|
284
|
+
# or from modules earlier runs left in the Hugging Face caches, which offline mode still loads. The caches
|
|
285
|
+
# are therefore pointed at empty directories of this export; a local model needs nothing from them.
|
|
286
|
+
def converter_env(dir)
|
|
287
|
+
{
|
|
288
|
+
'HF_HUB_OFFLINE' => '1',
|
|
289
|
+
'TRANSFORMERS_OFFLINE' => '1',
|
|
290
|
+
'HF_HOME' => File.join(dir, 'hf-home'),
|
|
291
|
+
'HF_HUB_CACHE' => File.join(dir, 'hf-hub'),
|
|
292
|
+
'HF_MODULES_CACHE' => File.join(dir, 'hf-modules'),
|
|
293
|
+
'TRANSFORMERS_CACHE' => nil,
|
|
294
|
+
'HUGGINGFACE_HUB_CACHE' => nil
|
|
295
|
+
}
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
def run(argv, name, env = {})
|
|
299
|
+
begin
|
|
300
|
+
output, success = runner.call(argv, env)
|
|
301
|
+
rescue SystemCallError => e
|
|
302
|
+
raise DependencyError, "could not run #{name} (#{argv.first}): #{e.message}"
|
|
303
|
+
end
|
|
304
|
+
return if success
|
|
305
|
+
|
|
306
|
+
tail = output.to_s.lines.last(20).join
|
|
307
|
+
|
|
308
|
+
raise ExportError, "#{name} failed:\n#{tail}"
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
# The converter runs in its own process with the interpreter RPEFT uses, so it sees the same packages
|
|
312
|
+
# without loading torch a second time into this process through PyCall.
|
|
313
|
+
def python
|
|
314
|
+
require_relative 'backend/python'
|
|
315
|
+
|
|
316
|
+
Backend::Python.default_python || 'python3'
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
def verify(path, name)
|
|
320
|
+
header = File.file?(path) ? File.binread(path, MAGIC.bytesize) : nil
|
|
321
|
+
|
|
322
|
+
raise ExportError, "#{name} did not write a GGUF file" unless header == MAGIC
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
# A hard link puts the file at the output in one step and fails if anything is there by now, so a file
|
|
326
|
+
# another process created since output_path checked is neither replaced nor removed.
|
|
327
|
+
def publish(staged, output)
|
|
328
|
+
File.link(staged, output)
|
|
329
|
+
rescue Errno::EEXIST
|
|
330
|
+
raise ConfigurationError, "output #{output} already exists; remove it or choose another path"
|
|
331
|
+
rescue Errno::EPERM, Errno::ENOTSUP, Errno::EOPNOTSUPP
|
|
332
|
+
copy_exclusively(staged, output)
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
# Some file systems, such as exFAT, have no hard links. Creating the output exclusively keeps the same
|
|
336
|
+
# guarantee at the cost of a copy, and a file this creates is the only one a failed copy removes.
|
|
337
|
+
def copy_exclusively(staged, output)
|
|
338
|
+
created = false
|
|
339
|
+
|
|
340
|
+
File.open(output, File::WRONLY | File::CREAT | File::EXCL | File::BINARY) do |file|
|
|
341
|
+
created = true
|
|
342
|
+
|
|
343
|
+
IO.copy_stream(staged, file)
|
|
344
|
+
end
|
|
345
|
+
rescue Errno::EEXIST
|
|
346
|
+
raise ConfigurationError, "output #{output} already exists; remove it or choose another path"
|
|
347
|
+
rescue StandardError
|
|
348
|
+
File.delete(output) if created
|
|
349
|
+
raise
|
|
350
|
+
end
|
|
351
|
+
end
|
|
352
|
+
end
|
|
353
|
+
end
|
data/lib/rpeft/lora/adapter.rb
CHANGED
|
@@ -84,8 +84,8 @@ module RPEFT
|
|
|
84
84
|
self
|
|
85
85
|
end
|
|
86
86
|
|
|
87
|
-
# Merges the learned
|
|
88
|
-
# (W = W0 + B A) and returns the resulting standalone Model.
|
|
87
|
+
# Merges the learned update into the base model weights
|
|
88
|
+
# (W = W0 + (alpha / r) B A) and returns the resulting standalone Model.
|
|
89
89
|
def merge(output_dir: nil)
|
|
90
90
|
unless base_model
|
|
91
91
|
raise MergeError, 'base model is unknown; pass base_model: to Adapter.load ' \
|
data/lib/rpeft/lora.rb
CHANGED
|
@@ -7,17 +7,18 @@ require 'tmpdir'
|
|
|
7
7
|
|
|
8
8
|
module RPEFT
|
|
9
9
|
# LoRA fine-tuning. Keeps the base model weights W0 frozen and learns
|
|
10
|
-
# a low-rank update
|
|
10
|
+
# a low-rank update of rank r, scaled by alpha / r:
|
|
11
11
|
#
|
|
12
|
-
# W = W0 +
|
|
12
|
+
# W = W0 + delta W
|
|
13
|
+
# delta W ~= (alpha / r) B A
|
|
13
14
|
#
|
|
14
|
-
# The `rank:`
|
|
15
|
+
# The `rank:` and `alpha:` options are exactly that r and alpha.
|
|
15
16
|
module LoRA
|
|
16
17
|
POSITIVE_INTEGER_OPTIONS = %i(rank epochs batch_size max_length).freeze
|
|
17
18
|
POSITIVE_NUMBER_OPTIONS = %i(alpha learning_rate).freeze
|
|
18
19
|
|
|
19
20
|
class << self
|
|
20
|
-
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, output_dir: nil, device: :auto, checkpoints: false, resume: false)
|
|
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
22
|
options = {
|
|
22
23
|
rank: rank,
|
|
23
24
|
alpha: alpha,
|
|
@@ -27,6 +28,7 @@ module RPEFT
|
|
|
27
28
|
batch_size: batch_size,
|
|
28
29
|
learning_rate: learning_rate,
|
|
29
30
|
max_length: max_length,
|
|
31
|
+
train_on_prompt: train_on_prompt,
|
|
30
32
|
checkpoints: checkpoints,
|
|
31
33
|
resume: resume
|
|
32
34
|
}
|
|
@@ -80,6 +82,13 @@ module RPEFT
|
|
|
80
82
|
end
|
|
81
83
|
validate_dropout(options[:dropout])
|
|
82
84
|
validate_target_modules(options[:target_modules])
|
|
85
|
+
validate_train_on_prompt(options[:train_on_prompt])
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def validate_train_on_prompt(train_on_prompt)
|
|
89
|
+
return if [true, false].include?(train_on_prompt)
|
|
90
|
+
|
|
91
|
+
raise ConfigurationError, "train_on_prompt must be true or false, got #{train_on_prompt.inspect}"
|
|
83
92
|
end
|
|
84
93
|
|
|
85
94
|
def validate_dropout(dropout)
|
|
@@ -102,12 +111,13 @@ module RPEFT
|
|
|
102
111
|
raise ConfigurationError, 'resume: true requires an explicit output_dir: to find the previous checkpoints'
|
|
103
112
|
end
|
|
104
113
|
|
|
105
|
-
#
|
|
114
|
+
# A chat transcript is rendered with the chat template and plain text is not, so a loss measured on one
|
|
115
|
+
# says little about a model trained on the other.
|
|
106
116
|
def coerce_eval_dataset(eval_dataset, training_dataset)
|
|
107
117
|
return nil unless eval_dataset
|
|
108
118
|
|
|
109
119
|
dataset = Dataset.coerce(eval_dataset)
|
|
110
|
-
return dataset if dataset.
|
|
120
|
+
return dataset if dataset.messages? == training_dataset.messages?
|
|
111
121
|
|
|
112
122
|
# Raised before train assigns the dataset, so its ensure clause cannot discard it.
|
|
113
123
|
dataset.discard unless dataset.equal?(eval_dataset)
|
|
@@ -133,6 +143,7 @@ module RPEFT
|
|
|
133
143
|
'epochs' => options[:epochs],
|
|
134
144
|
'batch_size' => options[:batch_size],
|
|
135
145
|
'learning_rate' => options[:learning_rate],
|
|
146
|
+
'train_on_prompt' => options[:train_on_prompt],
|
|
136
147
|
'logging_steps' => 5,
|
|
137
148
|
'seed' => 42,
|
|
138
149
|
'trust_remote_code' => false,
|
|
@@ -145,7 +156,10 @@ module RPEFT
|
|
|
145
156
|
'target_modules' => options[:target_modules]
|
|
146
157
|
}
|
|
147
158
|
}
|
|
148
|
-
|
|
159
|
+
if options[:eval_dataset]
|
|
160
|
+
payload['eval_dataset_path'] = options[:eval_dataset].path
|
|
161
|
+
payload['eval_dataset_format'] = options[:eval_dataset].backend_format
|
|
162
|
+
end
|
|
149
163
|
|
|
150
164
|
payload
|
|
151
165
|
end
|
|
@@ -192,6 +206,9 @@ module RPEFT
|
|
|
192
206
|
'batch_size' => options[:batch_size],
|
|
193
207
|
'learning_rate' => options[:learning_rate],
|
|
194
208
|
'max_length' => options[:max_length],
|
|
209
|
+
'train_on_prompt' => options[:train_on_prompt],
|
|
210
|
+
'skipped_examples' => result['skipped_examples'],
|
|
211
|
+
'eval_skipped_examples' => result['eval_skipped_examples'],
|
|
195
212
|
'device' => result['device'] || device.to_s,
|
|
196
213
|
'train_loss' => result['final_loss'],
|
|
197
214
|
'eval_loss' => result['eval_loss'],
|
data/lib/rpeft/model.rb
CHANGED
|
@@ -38,6 +38,15 @@ module RPEFT
|
|
|
38
38
|
self
|
|
39
39
|
end
|
|
40
40
|
|
|
41
|
+
# Writes the model to a single GGUF file for llama.cpp, Ollama, and other local runtimes, and returns its path.
|
|
42
|
+
# chat_template: false leaves out the chat template, for a model fine-tuned on plain text.
|
|
43
|
+
# See GGUF for the quantize: types and how the llama.cpp tools are found.
|
|
44
|
+
def export_gguf(output, quantize: :q8_0, chat_template: true, llama_cpp: nil, llama_quantize: nil)
|
|
45
|
+
GGUF.export(
|
|
46
|
+
path, output, quantize: quantize, chat_template: chat_template, llama_cpp: llama_cpp, llama_quantize: llama_quantize
|
|
47
|
+
)
|
|
48
|
+
end
|
|
49
|
+
|
|
41
50
|
# Generates a completion for the prompt. Decoding is greedy (and thus deterministic for a given model and prompt)
|
|
42
51
|
# unless temperature or top_p turns sampling on.
|
|
43
52
|
def generate(prompt, max_new_tokens: 64, device: :auto, temperature: nil, top_p: nil, seed: nil)
|
data/lib/rpeft/version.rb
CHANGED
data/lib/rpeft.rb
CHANGED
|
@@ -9,6 +9,7 @@ require_relative 'rpeft/dataset'
|
|
|
9
9
|
require_relative 'rpeft/messages'
|
|
10
10
|
require_relative 'rpeft/generation'
|
|
11
11
|
require_relative 'rpeft/model'
|
|
12
|
+
require_relative 'rpeft/gguf'
|
|
12
13
|
require_relative 'rpeft/lora'
|
|
13
14
|
require_relative 'rpeft/lora/adapter'
|
|
14
15
|
require_relative 'rpeft/backend'
|
|
@@ -11,8 +11,7 @@ def render(tokenizer, messages, add_generation_prompt=False):
|
|
|
11
11
|
messages, tokenize=False, add_generation_prompt=add_generation_prompt
|
|
12
12
|
)
|
|
13
13
|
|
|
14
|
-
# Tokenizers without a chat template (
|
|
15
|
-
# a deterministic rendering.
|
|
14
|
+
# Tokenizers without a chat template (some base models) still need a deterministic rendering.
|
|
16
15
|
rendered = "\n".join(
|
|
17
16
|
"%s: %s" % (message["role"], message["content"]) for message in messages
|
|
18
17
|
)
|
|
@@ -22,6 +21,40 @@ def render(tokenizer, messages, add_generation_prompt=False):
|
|
|
22
21
|
return rendered
|
|
23
22
|
|
|
24
23
|
|
|
24
|
+
def segments(tokenizer, messages):
|
|
25
|
+
"""Splits a rendered transcript into (text, trainable) pairs, trainable for the assistant's turns.
|
|
26
|
+
|
|
27
|
+
Each assistant turn is located by rendering the transcript up to its generation prompt and up to the
|
|
28
|
+
end of the turn: the difference is what the model writes at inference, the turn's end marker included.
|
|
29
|
+
"""
|
|
30
|
+
rendered = render(tokenizer, messages)
|
|
31
|
+
pairs = []
|
|
32
|
+
position = 0
|
|
33
|
+
for index, message in enumerate(messages):
|
|
34
|
+
# A turn opening the transcript answers nothing, such as a greeting, so it is read as context.
|
|
35
|
+
# Locating it would also mean rendering an empty transcript, which chat templates refuse.
|
|
36
|
+
if index == 0 or message.get("role") != "assistant":
|
|
37
|
+
continue
|
|
38
|
+
|
|
39
|
+
start = render(tokenizer, messages[:index], add_generation_prompt=True)
|
|
40
|
+
through = render(tokenizer, messages[: index + 1])
|
|
41
|
+
# Some templates render earlier turns differently once the conversation goes on, such as dropping
|
|
42
|
+
# reasoning from past replies. The turn then cannot be located, and guessing would train on the wrong text.
|
|
43
|
+
if not (rendered.startswith(through) and through.startswith(start) and len(start) >= position):
|
|
44
|
+
raise ValueError(
|
|
45
|
+
"the chat template renders earlier turns differently as the conversation goes on, so the "
|
|
46
|
+
"assistant's replies cannot be located; pass train_on_prompt: true (--train-on-prompt in the CLI) "
|
|
47
|
+
"to train on the whole transcript"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
pairs.append((rendered[position : len(start)], False))
|
|
51
|
+
pairs.append((rendered[len(start) : len(through)], True))
|
|
52
|
+
position = len(through)
|
|
53
|
+
|
|
54
|
+
pairs.append((rendered[position:], False))
|
|
55
|
+
return [(text, trainable) for text, trainable in pairs if text]
|
|
56
|
+
|
|
57
|
+
|
|
25
58
|
def writes_special_tokens(tokenizer):
|
|
26
59
|
"""Whether render's output already holds the special tokens, BOS included, that the model expects.
|
|
27
60
|
|