Detach legacy model mounts and migrate verified GGUF references
This commit is contained in:
1 parent
08e70c9113
commit
8cefa0b043
7 files changed
+260
-7
No files matched your search
@@ -0,0 +1,97 @@
|
||||
"""Import verified legacy reference weights into Deck; no GPU or service changes."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def digest(path):
|
||||
result = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(8 * 1024 * 1024), b''):
|
||||
result.update(block)
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def verify(path, source):
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size != source['size'] or digest(path) != source['sha256']:
|
||||
raise ValueError('Modelldatei stimmt nicht mit Original überein: ' + str(path))
|
||||
|
||||
|
||||
def migrate(state, legacy, sources):
|
||||
models = state / 'models'
|
||||
models.mkdir(parents=True, exist_ok=True)
|
||||
refs = state / 'reference-models'
|
||||
refs.mkdir(exist_ok=True)
|
||||
report = []
|
||||
for source in sources:
|
||||
ident = hashlib.sha256((source['repo'] + source['revision'] + source['file']).encode()).hexdigest()
|
||||
target = models / ident
|
||||
target.mkdir(exist_ok=True)
|
||||
weight = target / 'model.gguf'
|
||||
url = 'https://huggingface.co/' + source['repo'] + '/resolve/' + source['revision'] + '/' + urllib.parse.quote(source['file'], safe='/')
|
||||
upstream = json.load(urllib.request.urlopen('https://huggingface.co/api/models/' + source['repo'] + '/revision/' + source['revision'] + '?blobs=true', timeout=30))
|
||||
item = next(x for x in upstream['siblings'] if x['rfilename'] == source['file'])
|
||||
if upstream['sha'] != source['revision'] or item['size'] != source['size'] or item['lfs']['sha256'] != source['sha256']:
|
||||
raise ValueError('Originalquelle stimmt nicht überein: ' + source['repo'])
|
||||
action = 'already_present'
|
||||
if not weight.exists():
|
||||
if shutil.disk_usage(models).free < source['size'] + 10 * 1024**3:
|
||||
raise ValueError('Zu wenig Speicher für Modellübernahme.')
|
||||
partial = target / 'migration.partial'
|
||||
if partial.exists():
|
||||
raise ValueError('Unvollständige Übernahme vorhanden: ' + str(partial))
|
||||
old = legacy / source['folder'] / source['file']
|
||||
try:
|
||||
if old.is_file():
|
||||
verify(old, source)
|
||||
shutil.copyfile(old, partial)
|
||||
action = 'copied'
|
||||
else:
|
||||
with urllib.request.urlopen(url, timeout=60) as remote, partial.open('xb') as output:
|
||||
shutil.copyfileobj(remote, output, 8 * 1024 * 1024)
|
||||
action = 'downloaded'
|
||||
verify(partial, source)
|
||||
partial.replace(weight)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
else:
|
||||
verify(weight, source)
|
||||
entry = target / 'entry.json'
|
||||
if not entry.exists():
|
||||
metadata = {k: source[k] for k in ('repo', 'revision', 'file', 'size', 'sha256')}
|
||||
metadata.update(kind='chat', state='downloaded', runtime_ready=False, upstream_hash_verified=True, downloaded_at=time.time())
|
||||
temp = target / 'entry.tmp'
|
||||
temp.write_text(json.dumps(metadata, indent=2) + '\n')
|
||||
temp.replace(entry)
|
||||
else:
|
||||
metadata = json.loads(entry.read_text())
|
||||
if any(metadata.get(k) != source[k] for k in ('repo', 'revision', 'file', 'size', 'sha256')):
|
||||
raise ValueError('Metadatenkonflikt: ' + str(entry))
|
||||
if source['reference']:
|
||||
link = refs / source['file']
|
||||
relative = Path('..') / 'models' / ident / 'model.gguf'
|
||||
if link.is_symlink():
|
||||
if os.readlink(link) != str(relative):
|
||||
raise ValueError('Referenzkonflikt: ' + str(link))
|
||||
elif link.exists():
|
||||
raise ValueError('Referenzkonflikt: ' + str(link))
|
||||
else:
|
||||
link.symlink_to(relative)
|
||||
report.append(dict(file=source['file'], model_id=ident, action=action, sha256=source['sha256'], url=url))
|
||||
print(source['file'] + ': ' + action + ', checksum verified', flush=True)
|
||||
(state / 'reference-model-migration.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--state', type=Path, required=True)
|
||||
parser.add_argument('--legacy', type=Path, default=Path('/data/models'))
|
||||
args = parser.parse_args()
|
||||
migrate(args.state, args.legacy, json.loads(Path(__file__).with_name('reference_model_sources.json').read_text()))
|
||||
Reference in new issue
Block a user