diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..0ecb12fc1b0161f223a066e2732ab9caada6082b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,35 +1,6 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text +web/dist/media/posters/cat-active.jpg filter=lfs diff=lfs merge=lfs -text +web/dist/media/posters/pkg-arrive.jpg filter=lfs diff=lfs merge=lfs -text +web/dist/media/posters/pkg-taken.jpg filter=lfs diff=lfs merge=lfs -text +web/dist/media/posters/porch-empty.jpg filter=lfs diff=lfs merge=lfs -text diff --git a/MEDIA-SOURCES.md b/MEDIA-SOURCES.md new file mode 100644 index 0000000000000000000000000000000000000000..0f08f1dde874be147d254617f7c2778f8d0dd493 --- /dev/null +++ b/MEDIA-SOURCES.md @@ -0,0 +1,61 @@ +# Sample video sources + +Short clips supplied for this household-observation evaluation. Source links are retained for attribution. Original videos and datasets have not been modified. + +| Clip | Title | Source | +|---|---|---| +| smartbench_0133 | 宠物在客厅活动 | https://www.youtube.com/watch?v=jR4r4-sV5sU | +| smartbench_0880 | 空客厅后宠物进入 | https://www.youtube.com/watch?v=v5aU-eSFzK4 | +| smartbench_0036 | 人与宠物日常互动 | https://www.youtube.com/watch?v=c4BiMNV5dME | +| smartbench_0188 | 幼犬翻越围栏 | https://www.youtube.com/watch?v=uUsuo2hKqnQ | +| smartbench_0630 | 宠物撕咬纸巾 | https://www.youtube.com/watch?v=IAUXOVtZqNk | +| smartbench_0276 | 配送员放下包裹 | https://www.youtube.com/watch?v=_iV2anL2SKE | +| smartbench_0266 | 住户取走包裹 | https://www.youtube.com/watch?v=_xg3SH6qu1c | +| smartbench_0551 | 门口人员拆开包裹 | https://www.youtube.com/watch?v=EXEg6CfzW70 | +| smartbench_0216 | 住户离开后空门廊 | https://www.youtube.com/watch?v=OvBzOodJ31E | +| smartbench_0321 | 人与宠物回屋后空门廊 | https://www.youtube.com/watch?v=FuDb8E9G6q4 | +| smartbench_0083 | 夜间人员进入后院 | https://www.youtube.com/watch?v=yT7qfBXOGLw | +| smartbench_0094 | 夜间人员进入围栏庭院 | https://www.youtube.com/watch?v=ArFLLlLjfXw | +| smartbench_0007 | 熊进入后院翻垃圾桶 | https://www.youtube.com/watch?v=GfNH24LsSh8 | +| smartbench_0058 | 人与狗在院内活动 | https://www.youtube.com/watch?v=TnjOgP6IvU8 | +| smartbench_0290 | 后院鸟类在喂食器活动 | https://www.youtube.com/watch?v=XWCCEksks5U | +| smartbench_0643 | 住户回屋后空庭院门口 | https://www.youtube.com/watch?v=5Xy1MJ6hXKc | +| negative_01 | 沙发区无人活动_纸袋与箱子保持不变 | https://changedetection.net/dataset2014/ | +| negative_02 | 沙发区无人活动_箱子保持不变 | https://changedetection.net/dataset2014/ | +| negative_03 | 人和宠物回屋后空门廊 | https://www.youtube.com/watch?v=FuDb8E9G6q4 | +| negative_04 | 夜间人员离开后空庭院 | https://www.youtube.com/watch?v=ArFLLlLjfXw | +| negative_05 | 白天住户回屋后空庭院 | https://www.youtube.com/watch?v=5Xy1MJ6hXKc | +| negative_06 | 室外入口无人员_树影自然变化 | https://changedetection.net/dataset2014/ | +| S01 | 住户带包离家与门边钥匙动作 | https://www.youtube.com/watch?v=jNsO1K0mRwI | +| S02 | 住户带包靠近门并进屋 | https://www.youtube.com/watch?v=fyeQn4V8cHU | +| S03 | 孩子背书包离家_到家反例 | https://www.youtube.com/watch?v=z-TMWr0axSo | +| S04 | 放学儿童在门口交谈 | https://www.youtube.com/watch?v=CSM5AuDQzwc | +| S05 | 校车旁儿童回到门廊 | https://www.youtube.com/watch?v=X5sIOHuLyAw | +| S06 | 背书包儿童进入室内 | https://www.youtube.com/watch?v=-3yHkj7dPvA | +| S07 | 儿童入户后受惊跌倒_终态反例 | https://www.youtube.com/watch?v=-3yHkj7dPvA | +| S08 | 门廊清扫过程 | https://www.youtube.com/watch?v=sZ9ij4A0REg | +| S09 | 远处吸尘动作_微小目标无法确认 | https://www.youtube.com/watch?v=_Psi3NnuNiw | +| S10 | 宠物休息与扫地机器人活动 | https://www.youtube.com/watch?v=6xZVT_HphuM | +| S11 | 夜视猫进食并间歇抬头 | https://www.youtube.com/watch?v=17_N3EJXNwg | +| S12 | 猫在食盆旁抬头暂停_进食对照 | https://www.youtube.com/watch?v=17_N3EJXNwg | +| S13 | 两只猫在食盆附近互动 | https://www.youtube.com/watch?v=bK0HH-YZTQ4 | +| S14 | 松鼠翻动门口零食篮 | https://www.youtube.com/watch?v=M-R95X8bk94 | +| S15 | 狗咬鞋_与玩具区分 | https://www.youtube.com/watch?v=qPVd5EP6vRQ | +| S16 | 宠物贴近镜头造成遮挡 | https://www.youtube.com/watch?v=qPVd5EP6vRQ | +| S17 | 猫在玩具旁休息 | https://www.youtube.com/watch?v=nVkLviQSlcY | +| S18 | 猫贴镜头_视野与夜视切换 | https://www.youtube.com/watch?v=nVkLviQSlcY | +| S19 | 夜间蜘蛛靠近镜头 | https://www.youtube.com/watch?v=BiE85wTQvpE | +| S20 | 狗下桌后遮挡镜头 | https://www.youtube.com/watch?v=3AwEol8eZ0M | +| S21 | 院内晾衣被逐件收下 | https://www.youtube.com/watch?v=Kdefe5JM0xM | +| S22 | 乌龟推开庭院门后离开 | https://www.youtube.com/watch?v=lPfU3YZaCes | +| S23 | 宠物店监控_手部遮住微小乌龟 | https://www.youtube.com/watch?v=FPgvMrguuPs | +| S24 | 厨房窗户开关动作 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | +| S25 | 逆光窗户动作与携包经过 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | +| S26 | 收拾衣物与篮子 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | +| S27 | 厨房扫地_局部视野 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | +| S28 | 门边手部小物体_钥匙可观察性 | https://www.youtube.com/watch?v=jNsO1K0mRwI | +| S29 | 狗打开柜门并拉扯垃圾袋 | https://www.youtube.com/watch?v=-82STtPbfEc | +| S30 | 人员拿包裹时身体遮挡 | https://www.youtube.com/watch?v=Xl-R3YCQRkY | +| S31 | 离家后短暂返回门口 | https://www.youtube.com/watch?v=WRnhem3hsxc | +| S32 | 清理桌面并擦拭_表演采集 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | +| S33 | 固定机位车库清扫 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip | \ No newline at end of file diff --git a/README.md b/README.md index 05cdf98bf5e5099e3534deb3d20f739c92ffeb0e..afc7b52054006ef88f2c08a0fc1c278cb4081fee 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,49 @@ --- -title: OneAlign (Visual Quality/Aesthetic Scorer) -emoji: ⚖️ +title: Home Pulse +emoji: 🏡 colorFrom: green -colorTo: red +colorTo: yellow sdk: gradio -sdk_version: 4.12.0 +sdk_version: 6.30.0 +python_version: 3.12 app_file: app.py -pinned: true -license: mit -python_version: 3.10.14 +pinned: false +short_description: 用一句话设置家庭关注,确认对象,再交给视觉 AI 观察。 +tags: + - zerogpu + - computer-vision + - smart-home +models: + - mohit67890/imajev-4b + - Qwen/Qwen3.5-4B --- -arxiv.org/abs/2312.17090 +# Home Pulse -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file +家的消息,刚刚好。 + +**说明需求 → 看图确认对象与范围 → 澄清触发条件 → jev 试观察 → 启用 → 记忆复用。** + +This Space keeps the custom React interface and deterministic Node.js contract engine on free CPU hardware. Kimi handles user intent and visual grounding; visual decisions use the documented API of [the author's imajev Space](https://huggingface.co/spaces/mohit67890/imajev), running on HF ZeroGPU. The browser calls Gradio and the gateway forwards the visitor's `x-ip-token` to the model Space, following HF's cross-Space quota protocol. A short-lived authenticated loopback bridge connects visual responses to the rule engine. + +## Run and configure + +- `ANKER_KIMI_API_KEY`: server-side Space Secret for the competition Kimi API. +- Web hardware: **CPU Basic**. Visual backend: shared **ZeroGPU**. No paid hardware is requested. +- Open the direct `.hf.space` address to use the complete app on desktop or mobile browsers. +- Each browser has its own random workspace credential. Its memories, uploads, contracts and metrics are isolated from other visitors. Clearing browser storage also removes that browser's workspace credential. +- Free GPU allocation may queue and is subject to Hugging Face's visitor quota. Continuous observation runs while the observation page is open. +- Application data lives on the Space's temporary disk. Export important records before a rebuild; free Space storage is not a durable database. +- Task setup uses Kimi; images used for visual execution go to the HF Space. Secrets, local personal memories and local execution logs are excluded from the repository. + +## Models and attribution + +- [Imajev](https://github.com/mohit67890/imajev), by Mohit Garg, Apache-2.0. Only the required unmodified inference source is included under `upstream/`; its license is retained. +- [mohit67890/imajev-4b](https://huggingface.co/mohit67890/imajev-4b), adapter revision `f8d8234cebc6c99065c07731e59716dc0a6e27ab`. +- [Qwen/Qwen3.5-4B](https://huggingface.co/Qwen/Qwen3.5-4B), revision `851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a`, Apache-2.0. +- The shared model service manages its own model revision; requests enable its calibration and resize images to 640 pixels. It can update or be temporarily unavailable. Local NF4 results are not a claim about this hosted runtime. +- `app_zerogpu.py` and `requirements-zerogpu.txt` retain the separate own-GPU deployment option. That variant downloads the pinned revisions above from HF and uses BF16. It requires an account with ZeroGPU hosting access. +- Original model files are not modified or republished. +- Sample video source attribution is preserved in `media-library/说明与索引/完整素材索引.json` and `MEDIA-SOURCES.md`. + +The app provides image/video observation, bounded rule execution, on-page notifications, memories and operational metrics. Hardware camera events and phone push notifications are not connected. diff --git a/app.py b/app.py index 460a2cf7113bfd2c350255b3983ff12008802a49..5e11d9cfe61737c29d87d7f3ac285c338591f361 100644 --- a/app.py +++ b/app.py @@ -1,95 +1,136 @@ -import gradio as gr - -import argparse -import datetime -import json -import os -import time - -import gradio as gr -import requests -from PIL import Image - -from q_align.model.builder import load_pretrained_model - -from q_align.conversation import (default_conversation, conv_templates, - SeparatorStyle) -from q_align.constants import LOGDIR -from q_align.utils import (build_logger, server_error_msg, - violates_moderation, moderation_msg) - -from q_align.evaluate.scorer import QAlignScorer, QAlignAestheticScorer, QAlignVideoScorer - -import gradio as gr - -def load_video(video_file): - from decord import VideoReader - vr = VideoReader(video_file) - - # Get video frame rate - fps = vr.get_avg_fps() - - # Calculate frame indices for 1fps - frame_indices = [int(fps * i) for i in range(int(len(vr) / fps))] - frames = vr.get_batch(frame_indices).asnumpy() - return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))] - - -pretrained="q-future/one-align" -device="cuda:0" -tokenizer, model, image_processor, _ = load_pretrained_model(pretrained, None, "mplug_owl2", device=device) - -iqa_scorer = QAlignScorer(tokenizer=tokenizer, model=model, image_processor=image_processor) -iaa_scorer = QAlignAestheticScorer(tokenizer=tokenizer, model=model, image_processor=image_processor) -vqa_scorer = QAlignVideoScorer(tokenizer=tokenizer, model=model, image_processor=image_processor) - -scorers = {"Image Aesthetics (IAA)": iaa_scorer, "Image Quality (IQA)": iqa_scorer, "Video Quality (VQA)": vqa_scorer} - -LEVELS = ["excellent (5)", "good (4)", "fair (3)", "poor (2)", "bad (1)"] -scores = [5,4,3,2,1] -def image_classifier(input_img, input_vid, scorer_type): - if scorer_type is None: - scorer_type = "Image Quality (IQA)" - this_scorer = scorers[scorer_type] - if input_vid is not None: - input_ = load_video(input_vid) - elif input_img is not None: - input_ = [input_img] - if "Video" in scorer_type: - input_ = [input_] - probs = this_scorer(input_).mean(0).tolist() - prob_dict = {LEVEL: prob for LEVEL, prob in zip(LEVELS, probs)} - score = sum([prob * score for score, prob in zip(scores, probs)]) - return prob_dict, score - -title_markdown = (""" - -
- -
- -

If you like the OneScorer, please give us a star ✨ on [GitHub] for latest update.

- -
-
- - - - -
-
- -""") - - -input_img = gr.Image(type='pil', label="Upload an Image") -input_vid = gr.Video(label="Upload a Video (will INGORE the image if a video is uploaded)",sources=["upload"]) -radio = gr.Radio(["Image Aesthetics (IAA)", "Image Quality (IQA)", "Video Quality (VQA)"], label="Task", info="Which Scorer will you need?") - -input_img = gr.Image(type='pil', label="Upload an Image") - -labels = gr.Label(label="Probabilities of rating levels:") -number = gr.Number(label="Output score:", info="Range in [1,5]. Higher is better.", precision=4) -demo = gr.Interface(fn=image_classifier, inputs=[input_img, input_vid, radio], outputs=[labels, number], description=title_markdown, examples=[["fig/eiffel_a.jpg", None, "Image Aesthetics (IAA)"], ["fig/singapore_flyer_2.jpg", None, "Image Quality (IQA)"], ["fig/none.png", "fig/10244479353.mp4", "Video Quality (VQA)"]], article="This is the Scorer Demo as Proposed by Paper: 'Q-Align: Teaching LMMs for Visual Scoring via Discrete Text-Defined Levels'. The proposed Q-Align achieves state-of-the-art performance on image quality assessment (IQA), image aesthetic assessment (IAA), as well as video quality assessment (VQA) tasks under the original LMM structure. With the syllabus, we further unify the three tasks into one model, termed the **OneAlign**, to which the demo corresponds.") -demo.launch() - +"""Home Pulse's React UI and Node contracts, with the public HF imajev GPU API.""" +from gradio_client import Client +import atexit +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import threading +import base64 +import io +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import gradio as gr +import httpx +from fastapi import Request +from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse +from fastapi.staticfiles import StaticFiles +from starlette.background import BackgroundTask + + +ROOT=Path(__file__).resolve().parent +DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse')) +INTERNAL_KEY=secrets.token_hex(32) +NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861')) +PORT=int(os.getenv('PORT','7860')) +WORKSPACE=re.compile(r'^[a-f0-9]{64}$') +VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$') +os.environ.setdefault('TOKENIZERS_PARALLELISM','false') +os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1') +os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False') +os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY, + HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model') + +node=shutil.which('node') +if not node: raise RuntimeError('Node.js is unavailable') +node_process=subprocess.Popen([node,str(ROOT/'web/server-bundle.mjs')],cwd=ROOT/'web') +atexit.register(node_process.terminate) + +REMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev') +app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None) + +class ModelBridge(BaseHTTPRequestHandler): + def do_POST(self): + if self.path!='/v1/systemone' or self.headers.get('X-Bridge-Key')!=INTERNAL_KEY: + self.send_error(403);return + try: + length=int(self.headers.get('Content-Length','0')) + if not 016_000_000:raise ValueError('Image dimensions too large') + image=original.convert('RGB');image.thumbnail((640,640));data=io.BytesIO();image.save(data,format='JPEG',quality=90) + resized.append('data:image/jpeg;base64,'+base64.b64encode(data.getvalue()).decode()) + payload['images']=resized + value=self.remote_client.predict(payload,api_name='/systemone') + body=json.dumps(value).encode();self.send_response(200) + except Exception as exc: + print('Visual request failed:',type(exc).__name__,str(exc)[:200],flush=True) + message='HF 免费 GPU 额度暂时用完,请在额度恢复后再观察。' if re.search('quota|exceeded',str(exc),re.I) else 'HF 视觉服务暂时未返回结果,请稍后重试。' + body=json.dumps({'error':message}).encode();self.send_response(503) + self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body) + def log_message(self,*args): pass + +@app.api(name='visual',concurrency_limit=1,api_visibility='undocumented') +def visual(route:str,body:str,workspace:str,request:gr.Request)->dict: + if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace): + return {'status':400,'body':{'error':'观察请求无效'}} + if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}} + # HF's documented cross-Space protocol preserves the visiting user's quota. + token=request.headers.get('x-ip-token','') if request else '' + remote=Client(REMOTE_SPACE,headers={'x-ip-token':token} if token else {},verbose=False) + class VisitorBridge(ModelBridge): + remote_client=remote + bridge=ThreadingHTTPServer(('127.0.0.1',0),VisitorBridge) + thread=threading.Thread(target=bridge.serve_forever,daemon=True);thread.start() + try: + with httpx.Client(trust_env=False,timeout=210) as client: + response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={ + 'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY, + 'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port)}) + return {'status':response.status_code,'body':response.json()} + finally: + bridge.shutdown();bridge.server_close() + +@app.get('/_model/v1/models') +def models(): + global model_health + if time.monotonic()-model_health[0]>45: + try: + info=httpx.get('https://huggingface.co/api/spaces/'+REMOTE_SPACE,timeout=5).json() + model_health=(time.monotonic(),info.get('runtime',{}).get('stage')=='RUNNING') + except Exception:model_health=(time.monotonic(),False) + if not model_health[1]:return JSONResponse({'error':'HF 视觉服务正在连接'},status_code=503) + return {'data':[{'id':'imajev-4b-hf-shared'}],'runtime':{'model':'imajev-4b-hf-shared','gpu':'HF ZeroGPU · 共享算力','memoryGiB':None,'quantization':'BF16 · 共享服务','maxImageSide':640}} +model_health=(0,False) + +@app.api_route('/api/{path:path}',methods=['GET','POST']) +async def api_proxy(path:str,request:Request): + workspace=request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','') + if not WORKSPACE.fullmatch(workspace):return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401) + if request.method=='POST' and VISUAL.fullmatch('/api/'+path): + return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400) + headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host')} + headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace}) + client=httpx.AsyncClient(trust_env=False,timeout=220) + try: + target=f'http://127.0.0.1:{NODE_PORT}/api/'+path+('?' + request.url.query if request.url.query else '') + outbound=client.build_request(request.method,target,headers=headers,content=request.stream()) + response=await client.send(outbound,stream=True) + except Exception: + await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502) + async def close(): await response.aclose();await client.aclose() + kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')} + return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close)) + +app.mount('/assets',StaticFiles(directory=ROOT/'web/dist/assets'),name='assets') +app.mount('/media',StaticFiles(directory=ROOT/'web/dist/media'),name='media') +html=(ROOT/'web/dist/index.html').read_text(encoding='utf-8').replace('','') +async def page():return HTMLResponse(html,headers={'Cache-Control':'no-cache'}) +for route in ('/','/home','/watches','/create','/memories','/events','/review','/insights','/privacy','/watch/{item_id}','/observe/{item_id}'): + app.add_api_route(route,page,methods=['GET'],include_in_schema=False) +@app.get('/favicon.svg') +def favicon(): + from fastapi.responses import FileResponse + return FileResponse(ROOT/'web/dist/favicon.svg') + +if __name__=='__main__': + app.launch(server_name='0.0.0.0',server_port=PORT,show_error=False) diff --git a/app_zerogpu.py b/app_zerogpu.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f98bea40659302e70351567e1d56b9dd4bd9f3 --- /dev/null +++ b/app_zerogpu.py @@ -0,0 +1,115 @@ +"""Home Pulse's React UI + Node contracts + Gradio/ZeroGPU visual execution.""" +import spaces # Must precede torch and model imports for ZeroGPU CUDA emulation. +import atexit +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import gradio as gr +import httpx +from fastapi import Request +from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse +from fastapi.staticfiles import StaticFiles +from starlette.background import BackgroundTask +from model_runtime import load_model, predict + +ROOT=Path(__file__).resolve().parent +DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse')) +INTERNAL_KEY=secrets.token_hex(32) +NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861')) +PORT=int(os.getenv('PORT','7860')) +WORKSPACE=re.compile(r'^[a-f0-9]{64}$') +VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$') +os.environ.setdefault('TOKENIZERS_PARALLELISM','false') +os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1') +os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False') +os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY, + HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model') + +node=shutil.which('node') +if not node: raise RuntimeError('Node.js is unavailable') +node_process=subprocess.Popen([node,str(ROOT/'web/server-bundle.mjs')],cwd=ROOT/'web') +atexit.register(node_process.terminate) + +backend,calibration=load_model() +app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None) + +class ModelBridge(BaseHTTPRequestHandler): + def do_POST(self): + if self.path!='/v1/systemone' or self.headers.get('X-Bridge-Key')!=INTERNAL_KEY: + self.send_error(403);return + try: + length=int(self.headers.get('Content-Length','0')) + if not 0dict: + if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace): + return {'status':400,'body':{'error':'观察请求无效'}} + if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}} + # This bridge lives inside the allocated GPU worker. The Node rule engine calls + # it synchronously while it checks the trial or advances a monitoring contract. + bridge=ThreadingHTTPServer(('127.0.0.1',0),ModelBridge) + thread=threading.Thread(target=bridge.serve_forever,daemon=True);thread.start() + try: + with httpx.Client(trust_env=False,timeout=115) as client: + response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={ + 'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY, + 'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port)}) + return {'status':response.status_code,'body':response.json()} + finally: + bridge.shutdown();bridge.server_close() + +@app.get('/_model/v1/models') +def models(): + return {'data':[{'id':backend.model}],'runtime':{'model':backend.model,'gpu':'HF ZeroGPU · 按需分配','memoryGiB':None,'quantization':'BF16','maxImageSide':640}} + +@app.api_route('/api/{path:path}',methods=['GET','POST']) +async def api_proxy(path:str,request:Request): + workspace=request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','') + if not WORKSPACE.fullmatch(workspace):return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401) + if request.method=='POST' and VISUAL.fullmatch('/api/'+path): + return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400) + headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host')} + headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace}) + client=httpx.AsyncClient(trust_env=False,timeout=220) + try: + target=f'http://127.0.0.1:{NODE_PORT}/api/'+path+('?' + request.url.query if request.url.query else '') + outbound=client.build_request(request.method,target,headers=headers,content=request.stream()) + response=await client.send(outbound,stream=True) + except Exception: + await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502) + async def close(): await response.aclose();await client.aclose() + kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')} + return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close)) + +app.mount('/assets',StaticFiles(directory=ROOT/'web/dist/assets'),name='assets') +app.mount('/media',StaticFiles(directory=ROOT/'web/dist/media'),name='media') +html=(ROOT/'web/dist/index.html').read_text(encoding='utf-8').replace('','') +async def page():return HTMLResponse(html,headers={'Cache-Control':'no-cache'}) +for route in ('/','/home','/watches','/create','/memories','/events','/review','/insights','/privacy','/watch/{item_id}','/observe/{item_id}'): + app.add_api_route(route,page,methods=['GET'],include_in_schema=False) +@app.get('/favicon.svg') +def favicon(): + from fastapi.responses import FileResponse + return FileResponse(ROOT/'web/dist/favicon.svg') + +if __name__=='__main__': + app.launch(server_name='0.0.0.0',server_port=PORT,show_error=False) diff --git a/fig/10102107193.mp4 b/fig/10102107193.mp4 deleted file mode 100644 index 18a5eb7634dea20715773204f45668946575163c..0000000000000000000000000000000000000000 --- a/fig/10102107193.mp4 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0139566e1e3ed9f452472cd444236f745e3dcce99b0648fb01d9a8835af25ef9 -size 1072646 diff --git a/fig/10244479353.mp4 b/fig/10244479353.mp4 deleted file mode 100644 index 4e4b7015ed11e69fb37f02e550db5d3e8ee8dd59..0000000000000000000000000000000000000000 --- a/fig/10244479353.mp4 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:154e74795d12bf904091cdc7479f997865dd6339c85040012e7cab28cd863e30 -size 1523613 diff --git a/fig/eiffel_a.jpg b/fig/eiffel_a.jpg deleted file mode 100644 index d6fb2702f3c77f8557a7a34a03f615da2fb122b7..0000000000000000000000000000000000000000 --- a/fig/eiffel_a.jpg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3622a90a5996034e3bfdde33cd39f429f8a97ed0a3c1226c9f94eda154d0a968 -size 3157631 diff --git a/fig/longgang_nightblur.png b/fig/longgang_nightblur.png deleted file mode 100644 index 10684281127c27d673855dc971ea2391e4cd1471..0000000000000000000000000000000000000000 --- a/fig/longgang_nightblur.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9f6abc40a22cc4cdd3b5a926566c901981e357be58324284b656872abf5964c3 -size 1671611 diff --git a/fig/none.png b/fig/none.png deleted file mode 100644 index ba12e44cf95a396d52ce01de9cca71bc17beebb6..0000000000000000000000000000000000000000 --- a/fig/none.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5df7644187513e706f6231d3a893a87db1931946c016eaa36c328d3e863af385 -size 25902 diff --git a/fig/onescorer.png b/fig/onescorer.png deleted file mode 100644 index a8cbc74a391cc90b3ca1195f769af71c2c9f93ed..0000000000000000000000000000000000000000 --- a/fig/onescorer.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7f926247ac9815f541673a37233915d079193d1ab306b3a9d4ea21d6d553e6a4 -size 283907 diff --git a/fig/singapore_flyer_2.jpg b/fig/singapore_flyer_2.jpg deleted file mode 100644 index a2d9ad4131f9d778f08159cf81aef54c7a711b02..0000000000000000000000000000000000000000 --- a/fig/singapore_flyer_2.jpg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:09f86ecd97a2a16a79a8ccbc3acc8d8fa435e53e34da6d9fe144083446d2c644 -size 144442 diff --git a/media-library/clips/S01.mp4 b/media-library/clips/S01.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..46fb5a19f21a59fd2117ab21a8b0b23040fdf045 --- /dev/null +++ b/media-library/clips/S01.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c011225e9859ee9301997f658b6ef254186c4617aeda8f27510491992a138cb4 +size 4431305 diff --git a/media-library/clips/S02.mp4 b/media-library/clips/S02.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..b0a6516d0e96a213a44ab9f57351c0b586d5e104 --- /dev/null +++ b/media-library/clips/S02.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1a4cc7124c1c10b3d7cda67163b50799cb6910552beba511702d88e072d416d +size 2468175 diff --git a/media-library/clips/S03.mp4 b/media-library/clips/S03.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..3c7d0e3c14f4bf11e2b794c8ad867388cf386c01 --- /dev/null +++ b/media-library/clips/S03.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:642764d1a6178c54d5b0e270b8e17a6ce5f66864b8a2267683f75012532c3ef0 +size 3445934 diff --git a/media-library/clips/S04.mp4 b/media-library/clips/S04.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8be184f642e7e75f5ab33bc75bc40bcab3527506 --- /dev/null +++ b/media-library/clips/S04.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:caef889954f5c202287bc6241c54e6d0579c98b0ae33cd0e841ed592ffe57484 +size 3033512 diff --git a/media-library/clips/S05.mp4 b/media-library/clips/S05.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..254dc71fdaa92d29f59667f3f07340ca29c32f1e --- /dev/null +++ b/media-library/clips/S05.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0e3b0927e29b937f362d318edc039140c32c97b5f2197ae74222027809a6e7a +size 7782483 diff --git a/media-library/clips/S06.mp4 b/media-library/clips/S06.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..e60a7ce85cec7105d9e3eafbbe8d41fdc0a776d3 --- /dev/null +++ b/media-library/clips/S06.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33051945cea04a96f12a66c1a919cd664fd941bc33b53246254e0007391ee935 +size 320723 diff --git a/media-library/clips/S07.mp4 b/media-library/clips/S07.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1eeb37ccd6f3679bbe20a8b4492dca09fb41b8ad --- /dev/null +++ b/media-library/clips/S07.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15e4666860a6dfc433cf230e21ae692197a811940c6d1a1f00f728db3833d3e5 +size 2867089 diff --git a/media-library/clips/S08.mp4 b/media-library/clips/S08.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..65a7c56e81fd0943b4c92d832741998720026939 --- /dev/null +++ b/media-library/clips/S08.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6583f1e22909aa4ac9570a65e9f6923f81d5e6d6b35869109f310c9983d7f37f +size 4094116 diff --git a/media-library/clips/S09.mp4 b/media-library/clips/S09.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..80331a144f4c7bab5362ba75bb939c887ee76b3b --- /dev/null +++ b/media-library/clips/S09.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51cbfe2e637f7418fabdd7a2ed825f027f5f34de54efc943af5faed173d135ec +size 4257452 diff --git a/media-library/clips/S10.mp4 b/media-library/clips/S10.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..993726fcef54a77cb638b4227afa3e0318946ba6 --- /dev/null +++ b/media-library/clips/S10.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f9e6e8ca19b976a4b84262647314c17b61312a4fcf542eb921684b4eb74839b +size 16885712 diff --git a/media-library/clips/S11.mp4 b/media-library/clips/S11.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..4d3c2c0433b65bf62e97d953e9611b44818d4aaa --- /dev/null +++ b/media-library/clips/S11.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ee21c33e798333bcd43436f38da39f8a0a773131487ad9585e77311854716ff +size 2509003 diff --git a/media-library/clips/S12.mp4 b/media-library/clips/S12.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..fcfb0b792d0f289b8f7122a95672fe1b25eb22dd --- /dev/null +++ b/media-library/clips/S12.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:003431be7a70d4f66324e4bff9b18e81fc9c8ccfa29c937d4080f8d824233068 +size 666171 diff --git a/media-library/clips/S13.mp4 b/media-library/clips/S13.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8ddcb24be049f4b91e2ce21c9aa16c38e48b4ad4 --- /dev/null +++ b/media-library/clips/S13.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:781f3430896c16fd03cb2c2735056f2eee65fc611c22c3f82935497554075876 +size 3593305 diff --git a/media-library/clips/S14.mp4 b/media-library/clips/S14.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a3696a5c1114ea54fb1733717e32dd9e861eecea --- /dev/null +++ b/media-library/clips/S14.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:908a45b1ab0b1156c5bd9d8f827b26d57a6a335296bb6c8d8b8eb8eaaf291d64 +size 1666677 diff --git a/media-library/clips/S15.mp4 b/media-library/clips/S15.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..28f3346a4feb9ff8ff4e390cecafae26ce479e8b --- /dev/null +++ b/media-library/clips/S15.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c0b85ed18e928fa5fe84abc083f8c3eb97a7f7ce1842697fe489bc1f5248ec1 +size 939520 diff --git a/media-library/clips/S16.mp4 b/media-library/clips/S16.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..73231a7443ac22585956c327035034113bb83be7 --- /dev/null +++ b/media-library/clips/S16.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e98bf467108fa1502b8a6fb916f0fe1a47c68b51f035f11753b5423cfa9b781a +size 1181814 diff --git a/media-library/clips/S17.mp4 b/media-library/clips/S17.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c782497a5de34eb8e346c935a8ac1dbf52d9d52a --- /dev/null +++ b/media-library/clips/S17.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f74beb2d80ea2c246d2407d6186f8c3f19ba06c125ebdffbd372a058e11422 +size 602318 diff --git a/media-library/clips/S18.mp4 b/media-library/clips/S18.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a6847b9feeda6fd0186265f3bc2fe31d396aaab9 --- /dev/null +++ b/media-library/clips/S18.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:891f90f23e85afc00d79637bd52f8847407a4ae29cb1808c5c5aa16aa16e327c +size 3365441 diff --git a/media-library/clips/S19.mp4 b/media-library/clips/S19.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..cf66abba23af29f8ae1022ef23f87374371a3cb4 --- /dev/null +++ b/media-library/clips/S19.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c3e8e84a9128391f12aeca8d5df3fdde7902ff95c6c65117ed8014bb9085296 +size 1292660 diff --git a/media-library/clips/S20.mp4 b/media-library/clips/S20.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..365d7b4fd963936b50ab817efb44853d06911f76 --- /dev/null +++ b/media-library/clips/S20.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db22363ad8304458d586979e866763a5a218ca3ded62ea95087697fa4d561ac0 +size 1399556 diff --git a/media-library/clips/S21.mp4 b/media-library/clips/S21.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..b2535fc123dd877dc3910ed0b2e04708cad92f94 --- /dev/null +++ b/media-library/clips/S21.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:564bca14aae364c1675d336a2bbc774e2710d257a5c814aff7d1c5fd6ab5a026 +size 8640133 diff --git a/media-library/clips/S22.mp4 b/media-library/clips/S22.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1d2ba03a7616f50af0a96f54dd20ac9a95322550 --- /dev/null +++ b/media-library/clips/S22.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33873bb3eda06024d63db739c07a0828291767ac619f08fc086e2de957cd855a +size 16668998 diff --git a/media-library/clips/S23.mp4 b/media-library/clips/S23.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1f3ea62bcdeb609f66b91f83901b49ff2af0d46a --- /dev/null +++ b/media-library/clips/S23.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5569f6fc913791de712ab586343a38c14e35d2b1143e5f59693281a0bcbf1b7e +size 1642478 diff --git a/media-library/clips/S24.mp4 b/media-library/clips/S24.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..0dfbaf8f60cefe13aec3cbe49418e3b72b672d0b --- /dev/null +++ b/media-library/clips/S24.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:488febab0e48543d1f392f6ef190f45363651efc2e49c4e06896f63321374d52 +size 1249496 diff --git a/media-library/clips/S25.mp4 b/media-library/clips/S25.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..7bc388ad98a1f3d0f6bcfc3b51cad84efb6c1c1f --- /dev/null +++ b/media-library/clips/S25.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77957d3920bd0ce617946acfcbb1b2f1fac0bbae129e8354510b087c917055d5 +size 1360843 diff --git a/media-library/clips/S26.mp4 b/media-library/clips/S26.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..64dd11843858ce2506465fd16b945a13351e2127 --- /dev/null +++ b/media-library/clips/S26.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4477b4649ff4ada0ba39b27c81f296cf2f12b64b99715ffc379c3eebc24b8820 +size 1214593 diff --git a/media-library/clips/S27.mp4 b/media-library/clips/S27.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..aa572319fa5d4a256a0532d1a6afbaf31e5af236 --- /dev/null +++ b/media-library/clips/S27.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a44680763f837410191ef618b7a3310ee7e178deb5d7372f4f621a43608dca33 +size 1394804 diff --git a/media-library/clips/S28.mp4 b/media-library/clips/S28.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..20b3b66631b6e8b912369423465571066353428a --- /dev/null +++ b/media-library/clips/S28.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ef2fff976523439d25b1bf2592f42f9628fde955568bd5f876f6b734fd1324d +size 1942713 diff --git a/media-library/clips/S29.mp4 b/media-library/clips/S29.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..533226be8c23ba89c3cc3448be2dd9951d384901 --- /dev/null +++ b/media-library/clips/S29.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42d548742da2a82971fc74e95bb56faf3d00490885b7d2c60120c2fc151de7c5 +size 7069638 diff --git a/media-library/clips/S30.mp4 b/media-library/clips/S30.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..36f80790cd2ae5352d6039ec4b44af672e96b1dd --- /dev/null +++ b/media-library/clips/S30.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f550a4980d685ab5af07dca3bcd15cc9afb376551e9f42d5797f5e700bd2bfb1 +size 1898144 diff --git a/media-library/clips/S31.mp4 b/media-library/clips/S31.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..64780e6cff3a3b42ebd1e3bc7dbc1343980e266b --- /dev/null +++ b/media-library/clips/S31.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f962b09ed65516dcc62b2e205680ee3771d6c38fae37d73e976d91ee01f80a2 +size 2524105 diff --git a/media-library/clips/S32.mp4 b/media-library/clips/S32.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..ad988205174acb82413815e9b126432ecd661958 --- /dev/null +++ b/media-library/clips/S32.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9487304f1cb3e3807b1c47dabbad80660779a91d17cb4e2caf750fe550014eb7 +size 1940356 diff --git a/media-library/clips/S33.mp4 b/media-library/clips/S33.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..bafbae6961adb4f7dcd3f86b2c9770768a35f325 --- /dev/null +++ b/media-library/clips/S33.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9111bed3120b857c5fcdf83a27c9c88a5eae6640ff237cc8570da0cc2f0b0be +size 2837778 diff --git a/media-library/clips/negative_01.mp4 b/media-library/clips/negative_01.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..84d36982fc7fd675f344e1cc6a2db077d5f461b6 Binary files /dev/null and b/media-library/clips/negative_01.mp4 differ diff --git a/media-library/clips/negative_02.mp4 b/media-library/clips/negative_02.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..d9a672ea7f32921c627c708c38882356194c52f2 Binary files /dev/null and b/media-library/clips/negative_02.mp4 differ diff --git a/media-library/clips/negative_03.mp4 b/media-library/clips/negative_03.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a61c75fc7f9ad63c70ac3648e03096ae55c29d12 --- /dev/null +++ b/media-library/clips/negative_03.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54287efc54404ee33e984c91ed327d0bdad7cd3315d2d0c00c84e5132e5f3f20 +size 215127 diff --git a/media-library/clips/negative_04.mp4 b/media-library/clips/negative_04.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..57ae24636510f837421068d73ca6eba500d75f52 --- /dev/null +++ b/media-library/clips/negative_04.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:685150db6e5cfd396f82e116e9fcaa83a6bdde634dd271d95a3e818280200903 +size 226630 diff --git a/media-library/clips/negative_05.mp4 b/media-library/clips/negative_05.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..777af0146ed53e3c2bfdb44c42702fa61e17f4b9 --- /dev/null +++ b/media-library/clips/negative_05.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67a70ed4e1c7b343eca6af014cc4cbd1df4b32358def273e1db45c20e7908ee4 +size 548387 diff --git a/media-library/clips/negative_06.mp4 b/media-library/clips/negative_06.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..4ddfdf6202dad030c61f20b25f49a8fa2ddb2b49 --- /dev/null +++ b/media-library/clips/negative_06.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4c8f26b01b29f925346a4fb9e6a8850515488836dfb004b2233c7b8e2aedba5 +size 581968 diff --git a/media-library/clips/smartbench_0007.mp4 b/media-library/clips/smartbench_0007.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..d1e08ce2dabadbac09c6a9e6243b26af791cd8cc --- /dev/null +++ b/media-library/clips/smartbench_0007.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a674d025922cf7ee6714d1181d5a34105427261c9630c8601e8e33cc88adad6a +size 3861778 diff --git a/media-library/clips/smartbench_0036.mp4 b/media-library/clips/smartbench_0036.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..410677192f8fcf5edbc4b02ae6ddbe67060d2b2b --- /dev/null +++ b/media-library/clips/smartbench_0036.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:557055b2fdc060a59396eb02fabf676beac72ac5e9f19785683a5190c89d3dc8 +size 1009363 diff --git a/media-library/clips/smartbench_0058.mp4 b/media-library/clips/smartbench_0058.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..7e941d6135763d361e5b818ae7db7c1fb6239218 --- /dev/null +++ b/media-library/clips/smartbench_0058.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:514dafc4deb7e95f72dca3906238e362c3c4ff50278ec17877c00979d1563495 +size 2553060 diff --git a/media-library/clips/smartbench_0083.mp4 b/media-library/clips/smartbench_0083.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..2b3873f1ca82df1d99d6c84f8d92bb2ae11a4b78 --- /dev/null +++ b/media-library/clips/smartbench_0083.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d987545482e4807ad9d7a9e1a663d62e2acac8eb6625e9aefaf4012f163e0a0 +size 870997 diff --git a/media-library/clips/smartbench_0094.mp4 b/media-library/clips/smartbench_0094.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c82e5fc607c5a6af98d287433c2dc6f20394eb0b --- /dev/null +++ b/media-library/clips/smartbench_0094.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffe719eef43291401f810c6d9fd0c6fc3956b7148ae85ace8d9ab87ba8b115cd +size 715787 diff --git a/media-library/clips/smartbench_0133.mp4 b/media-library/clips/smartbench_0133.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..771628c548e1427890cb7fb576c6e0b9733abe8e --- /dev/null +++ b/media-library/clips/smartbench_0133.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b80c6f6c21bd55830fbce317f49cb383de4b755710826400c8128ec1125ad9f6 +size 1827868 diff --git a/media-library/clips/smartbench_0188.mp4 b/media-library/clips/smartbench_0188.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..b08f1b2cd6e72256f738cfe6a6e4557c0f80ec43 --- /dev/null +++ b/media-library/clips/smartbench_0188.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ba00d512657f1a5ba7a53b0ac2127a9b959a101304f1896bb53000cf16e2ab5 +size 5279941 diff --git a/media-library/clips/smartbench_0216.mp4 b/media-library/clips/smartbench_0216.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c73eedde43a91d489f9a645d9bb5d0c6273be514 --- /dev/null +++ b/media-library/clips/smartbench_0216.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0fbda0816c4de68c65e59813d968a084176d616ba65bf6f762b8bfd7b96e5dd +size 1378625 diff --git a/media-library/clips/smartbench_0266.mp4 b/media-library/clips/smartbench_0266.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..9a72990a77d98f7cf10c4a7d86fbf9c0f0beea29 --- /dev/null +++ b/media-library/clips/smartbench_0266.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bfbe0fb55610d5b8872d575577ec62973093df443ef19dd7f5ceee1b075e8b6 +size 6682032 diff --git a/media-library/clips/smartbench_0276.mp4 b/media-library/clips/smartbench_0276.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..d4975aa08ee767fb98971c4c5f666ede2d86e308 --- /dev/null +++ b/media-library/clips/smartbench_0276.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c684e69201df8551f19a0fd8fd75f5dfb387ddda5f1a610fab2ee47a1abc5b3 +size 2820864 diff --git a/media-library/clips/smartbench_0290.mp4 b/media-library/clips/smartbench_0290.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..09d0eda794ad52bd8c566c7e9f024fd4fcfc2412 --- /dev/null +++ b/media-library/clips/smartbench_0290.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2baf8522ee94e05550a77518390112fb31a3a29ef34914b46927dbba508f7636 +size 8015107 diff --git a/media-library/clips/smartbench_0321.mp4 b/media-library/clips/smartbench_0321.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..abbdfb13402fa6e5fdc1b6c4aa94f280f8e00d83 --- /dev/null +++ b/media-library/clips/smartbench_0321.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6500c91c0709dca48284075a2b1f3a23bbab043de48a5c639b0fd2a355eddd85 +size 1080523 diff --git a/media-library/clips/smartbench_0551.mp4 b/media-library/clips/smartbench_0551.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a654048ee4448d600369515b95fd033cdd282546 --- /dev/null +++ b/media-library/clips/smartbench_0551.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0b361e3cd8ff64dc6e99bd1d525fe7bcc033e3b9b0099eca5aacbc4a41975a0 +size 5595639 diff --git a/media-library/clips/smartbench_0630.mp4 b/media-library/clips/smartbench_0630.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8e651452354101025226cb805f8794bcf156427e --- /dev/null +++ b/media-library/clips/smartbench_0630.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a77d7d6550a2880bdbb313fdda3d4f2118763cb0007af38b881fb3202a479d1 +size 2932409 diff --git a/media-library/clips/smartbench_0643.mp4 b/media-library/clips/smartbench_0643.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..f28183ef7a0a1322de5385ea64d410eceb539bee --- /dev/null +++ b/media-library/clips/smartbench_0643.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03cdcd4ff7423b286706feb5a9528cd22e5b0e6447e798b17d13cd0ae6968343 +size 3583144 diff --git a/media-library/clips/smartbench_0880.mp4 b/media-library/clips/smartbench_0880.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..fb0e9f0e618ca6a375aa168a2739e89379a76e24 --- /dev/null +++ b/media-library/clips/smartbench_0880.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88e8e935c56fdf3d130b5e2901710648421ecfa7ce567caf25810fa5dc9048e4 +size 4104584 diff --git "a/media-library/\350\257\264\346\230\216\344\270\216\347\264\242\345\274\225/\345\256\214\346\225\264\347\264\240\346\235\220\347\264\242\345\274\225.json" "b/media-library/\350\257\264\346\230\216\344\270\216\347\264\242\345\274\225/\345\256\214\346\225\264\347\264\240\346\235\220\347\264\242\345\274\225.json" new file mode 100644 index 0000000000000000000000000000000000000000..2356af91416505b038b65748f2f24ac6ea5b60ac --- /dev/null +++ "b/media-library/\350\257\264\346\230\216\344\270\216\347\264\242\345\274\225/\345\256\214\346\225\264\347\264\240\346\235\220\347\264\242\345\274\225.json" @@ -0,0 +1,497 @@ +[ + { + "clip_id": "smartbench_0133", + "title": "宠物在客厅活动", + "scene": "室内", + "source_id": "smartbench_0133", + "source_url": "https://www.youtube.com/watch?v=jR4r4-sV5sU", + "duration_s": 16.85, + "file": "clips/smartbench_0133.mp4" + }, + { + "clip_id": "smartbench_0880", + "title": "空客厅后宠物进入", + "scene": "室内", + "source_id": "smartbench_0880", + "source_url": "https://www.youtube.com/watch?v=v5aU-eSFzK4", + "duration_s": 36.067, + "file": "clips/smartbench_0880.mp4" + }, + { + "clip_id": "smartbench_0036", + "title": "人与宠物日常互动", + "scene": "室内", + "source_id": "smartbench_0036", + "source_url": "https://www.youtube.com/watch?v=c4BiMNV5dME", + "duration_s": 11.553, + "file": "clips/smartbench_0036.mp4" + }, + { + "clip_id": "smartbench_0188", + "title": "幼犬翻越围栏", + "scene": "室内", + "source_id": "smartbench_0188", + "source_url": "https://www.youtube.com/watch?v=uUsuo2hKqnQ", + "duration_s": 35.202, + "file": "clips/smartbench_0188.mp4" + }, + { + "clip_id": "smartbench_0630", + "title": "宠物撕咬纸巾", + "scene": "室内", + "source_id": "smartbench_0630", + "source_url": "https://www.youtube.com/watch?v=IAUXOVtZqNk", + "duration_s": 33.659, + "file": "clips/smartbench_0630.mp4" + }, + { + "clip_id": "smartbench_0276", + "title": "配送员放下包裹", + "scene": "门口", + "source_id": "smartbench_0276", + "source_url": "https://www.youtube.com/watch?v=_iV2anL2SKE", + "duration_s": 17.851, + "file": "clips/smartbench_0276.mp4" + }, + { + "clip_id": "smartbench_0266", + "title": "住户取走包裹", + "scene": "门口", + "source_id": "smartbench_0266", + "source_url": "https://www.youtube.com/watch?v=_xg3SH6qu1c", + "duration_s": 25.817, + "file": "clips/smartbench_0266.mp4" + }, + { + "clip_id": "smartbench_0551", + "title": "门口人员拆开包裹", + "scene": "门口", + "source_id": "smartbench_0551", + "source_url": "https://www.youtube.com/watch?v=EXEg6CfzW70", + "duration_s": 34.8, + "file": "clips/smartbench_0551.mp4" + }, + { + "clip_id": "smartbench_0216", + "title": "住户离开后空门廊", + "scene": "门口", + "source_id": "smartbench_0216", + "source_url": "https://www.youtube.com/watch?v=OvBzOodJ31E", + "duration_s": 20.27, + "file": "clips/smartbench_0216.mp4" + }, + { + "clip_id": "smartbench_0321", + "title": "人与宠物回屋后空门廊", + "scene": "门口", + "source_id": "smartbench_0321", + "source_url": "https://www.youtube.com/watch?v=FuDb8E9G6q4", + "duration_s": 21.855, + "file": "clips/smartbench_0321.mp4" + }, + { + "clip_id": "smartbench_0083", + "title": "夜间人员进入后院", + "scene": "庭院", + "source_id": "smartbench_0083", + "source_url": "https://www.youtube.com/watch?v=yT7qfBXOGLw", + "duration_s": 10.511, + "file": "clips/smartbench_0083.mp4" + }, + { + "clip_id": "smartbench_0094", + "title": "夜间人员进入围栏庭院", + "scene": "庭院", + "source_id": "smartbench_0094", + "source_url": "https://www.youtube.com/watch?v=ArFLLlLjfXw", + "duration_s": 13.68, + "file": "clips/smartbench_0094.mp4" + }, + { + "clip_id": "smartbench_0007", + "title": "熊进入后院翻垃圾桶", + "scene": "庭院", + "source_id": "smartbench_0007", + "source_url": "https://www.youtube.com/watch?v=GfNH24LsSh8", + "duration_s": 20.27, + "file": "clips/smartbench_0007.mp4" + }, + { + "clip_id": "smartbench_0058", + "title": "人与狗在院内活动", + "scene": "庭院", + "source_id": "smartbench_0058", + "source_url": "https://www.youtube.com/watch?v=TnjOgP6IvU8", + "duration_s": 22.089, + "file": "clips/smartbench_0058.mp4" + }, + { + "clip_id": "smartbench_0290", + "title": "后院鸟类在喂食器活动", + "scene": "庭院", + "source_id": "smartbench_0290", + "source_url": "https://www.youtube.com/watch?v=XWCCEksks5U", + "duration_s": 41.416, + "file": "clips/smartbench_0290.mp4" + }, + { + "clip_id": "smartbench_0643", + "title": "住户回屋后空庭院门口", + "scene": "庭院", + "source_id": "smartbench_0643", + "source_url": "https://www.youtube.com/watch?v=5Xy1MJ6hXKc", + "duration_s": 16.808, + "file": "clips/smartbench_0643.mp4" + }, + { + "clip_id": "negative_01", + "title": "沙发区无人活动_纸袋与箱子保持不变", + "scene": "室内", + "source_id": "cdnet_sofa", + "source_url": "https://changedetection.net/dataset2014/", + "duration_s": 5.0, + "file": "clips/negative_01.mp4" + }, + { + "clip_id": "negative_02", + "title": "沙发区无人活动_箱子保持不变", + "scene": "室内", + "source_id": "cdnet_sofa", + "source_url": "https://changedetection.net/dataset2014/", + "duration_s": 5.48, + "file": "clips/negative_02.mp4" + }, + { + "clip_id": "negative_03", + "title": "人和宠物回屋后空门廊", + "scene": "门口", + "source_id": "smartbench_0321", + "source_url": "https://www.youtube.com/watch?v=FuDb8E9G6q4", + "duration_s": 4.713, + "file": "clips/negative_03.mp4" + }, + { + "clip_id": "negative_04", + "title": "夜间人员离开后空庭院", + "scene": "庭院", + "source_id": "smartbench_0094", + "source_url": "https://www.youtube.com/watch?v=ArFLLlLjfXw", + "duration_s": 4.713, + "file": "clips/negative_04.mp4" + }, + { + "clip_id": "negative_05", + "title": "白天住户回屋后空庭院", + "scene": "庭院", + "source_id": "smartbench_0643", + "source_url": "https://www.youtube.com/watch?v=5Xy1MJ6hXKc", + "duration_s": 2.835, + "file": "clips/negative_05.mp4" + }, + { + "clip_id": "negative_06", + "title": "室外入口无人员_树影自然变化", + "scene": "门口", + "source_id": "cdnet_backdoor", + "source_url": "https://changedetection.net/dataset2014/", + "duration_s": 28.48, + "file": "clips/negative_06.mp4" + }, + { + "clip_id": "S01", + "title": "住户带包离家与门边钥匙动作", + "scene": "门口", + "source_id": "smartbench_0217", + "source_url": "https://www.youtube.com/watch?v=jNsO1K0mRwI", + "duration_s": 20.503, + "file": "clips/S01.mp4" + }, + { + "clip_id": "S02", + "title": "住户带包靠近门并进屋", + "scene": "门口", + "source_id": "smartbench_0203", + "source_url": "https://www.youtube.com/watch?v=fyeQn4V8cHU", + "duration_s": 12.655, + "file": "clips/S02.mp4" + }, + { + "clip_id": "S03", + "title": "孩子背书包离家_到家反例", + "scene": "门口", + "source_id": "smartbench_0033", + "source_url": "https://www.youtube.com/watch?v=z-TMWr0axSo", + "duration_s": 16.486, + "file": "clips/S03.mp4" + }, + { + "clip_id": "S04", + "title": "放学儿童在门口交谈", + "scene": "门口", + "source_id": "smartbench_0398", + "source_url": "https://www.youtube.com/watch?v=CSM5AuDQzwc", + "duration_s": 44.002, + "file": "clips/S04.mp4" + }, + { + "clip_id": "S05", + "title": "校车旁儿童回到门廊", + "scene": "门口", + "source_id": "smartbench_0877", + "source_url": "https://www.youtube.com/watch?v=X5sIOHuLyAw", + "duration_s": 31.031, + "file": "clips/S05.mp4" + }, + { + "clip_id": "S06", + "title": "背书包儿童进入室内", + "scene": "室内", + "source_id": "smartbench_0277", + "source_url": "https://www.youtube.com/watch?v=-3yHkj7dPvA", + "duration_s": 2.211, + "file": "clips/S06.mp4" + }, + { + "clip_id": "S07", + "title": "儿童入户后受惊跌倒_终态反例", + "scene": "室内", + "source_id": "smartbench_0277", + "source_url": "https://www.youtube.com/watch?v=-3yHkj7dPvA", + "duration_s": 15.807, + "file": "clips/S07.mp4" + }, + { + "clip_id": "S08", + "title": "门廊清扫过程", + "scene": "门口", + "source_id": "smartbench_0011", + "source_url": "https://www.youtube.com/watch?v=sZ9ij4A0REg", + "duration_s": 16.997, + "file": "clips/S08.mp4" + }, + { + "clip_id": "S09", + "title": "远处吸尘动作_微小目标无法确认", + "scene": "室内", + "source_id": "smartbench_0259", + "source_url": "https://www.youtube.com/watch?v=_Psi3NnuNiw", + "duration_s": 53.011, + "file": "clips/S09.mp4" + }, + { + "clip_id": "S10", + "title": "宠物休息与扫地机器人活动", + "scene": "室内", + "source_id": "smartbench_0992", + "source_url": "https://www.youtube.com/watch?v=6xZVT_HphuM", + "duration_s": 62.903, + "file": "clips/S10.mp4" + }, + { + "clip_id": "S11", + "title": "夜视猫进食并间歇抬头", + "scene": "室内", + "source_id": "smartbench_0142", + "source_url": "https://www.youtube.com/watch?v=17_N3EJXNwg", + "duration_s": 33.599, + "file": "clips/S11.mp4" + }, + { + "clip_id": "S12", + "title": "猫在食盆旁抬头暂停_进食对照", + "scene": "室内", + "source_id": "smartbench_0142", + "source_url": "https://www.youtube.com/watch?v=17_N3EJXNwg", + "duration_s": 7.341, + "file": "clips/S12.mp4" + }, + { + "clip_id": "S13", + "title": "两只猫在食盆附近互动", + "scene": "庭院", + "source_id": "smartbench_0641", + "source_url": "https://www.youtube.com/watch?v=bK0HH-YZTQ4", + "duration_s": 16.114, + "file": "clips/S13.mp4" + }, + { + "clip_id": "S14", + "title": "松鼠翻动门口零食篮", + "scene": "门口", + "source_id": "smartbench_0294", + "source_url": "https://www.youtube.com/watch?v=M-R95X8bk94", + "duration_s": 19.574, + "file": "clips/S14.mp4" + }, + { + "clip_id": "S15", + "title": "狗咬鞋_与玩具区分", + "scene": "室内", + "source_id": "smartbench_0205", + "source_url": "https://www.youtube.com/watch?v=qPVd5EP6vRQ", + "duration_s": 9.009, + "file": "clips/S15.mp4" + }, + { + "clip_id": "S16", + "title": "宠物贴近镜头造成遮挡", + "scene": "室内", + "source_id": "smartbench_0205", + "source_url": "https://www.youtube.com/watch?v=qPVd5EP6vRQ", + "duration_s": 6.006, + "file": "clips/S16.mp4" + }, + { + "clip_id": "S17", + "title": "猫在玩具旁休息", + "scene": "室内", + "source_id": "smartbench_0379", + "source_url": "https://www.youtube.com/watch?v=nVkLviQSlcY", + "duration_s": 12.012, + "file": "clips/S17.mp4" + }, + { + "clip_id": "S18", + "title": "猫贴镜头_视野与夜视切换", + "scene": "室内", + "source_id": "smartbench_0379", + "source_url": "https://www.youtube.com/watch?v=nVkLviQSlcY", + "duration_s": 15.015, + "file": "clips/S18.mp4" + }, + { + "clip_id": "S19", + "title": "夜间蜘蛛靠近镜头", + "scene": "庭院", + "source_id": "smartbench_0085", + "source_url": "https://www.youtube.com/watch?v=BiE85wTQvpE", + "duration_s": 10.518, + "file": "clips/S19.mp4" + }, + { + "clip_id": "S20", + "title": "狗下桌后遮挡镜头", + "scene": "室内", + "source_id": "smartbench_0081", + "source_url": "https://www.youtube.com/watch?v=3AwEol8eZ0M", + "duration_s": 13.862, + "file": "clips/S20.mp4" + }, + { + "clip_id": "S21", + "title": "院内晾衣被逐件收下", + "scene": "庭院", + "source_id": "web_laundry_rain", + "source_url": "https://www.youtube.com/watch?v=Kdefe5JM0xM", + "duration_s": 90.395, + "file": "clips/S21.mp4" + }, + { + "clip_id": "S22", + "title": "乌龟推开庭院门后离开", + "scene": "庭院", + "source_id": "web_tortoise_escape", + "source_url": "https://www.youtube.com/watch?v=lPfU3YZaCes", + "duration_s": 64.0, + "file": "clips/S22.mp4" + }, + { + "clip_id": "S23", + "title": "宠物店监控_手部遮住微小乌龟", + "scene": "室内", + "source_id": "web_tortoise_small", + "source_url": "https://www.youtube.com/watch?v=FPgvMrguuPs", + "duration_s": 10.21, + "file": "clips/S23.mp4" + }, + { + "clip_id": "S24", + "title": "厨房窗户开关动作", + "scene": "室内", + "source_id": "charades_Z1LVD", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 22.152, + "file": "clips/S24.mp4" + }, + { + "clip_id": "S25", + "title": "逆光窗户动作与携包经过", + "scene": "室内", + "source_id": "charades_AGELP", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 29.164, + "file": "clips/S25.mp4" + }, + { + "clip_id": "S26", + "title": "收拾衣物与篮子", + "scene": "室内", + "source_id": "charades_QLWQ4", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 45.975, + "file": "clips/S26.mp4" + }, + { + "clip_id": "S27", + "title": "厨房扫地_局部视野", + "scene": "室内", + "source_id": "charades_FU2HI", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 36.455, + "file": "clips/S27.mp4" + }, + { + "clip_id": "S28", + "title": "门边手部小物体_钥匙可观察性", + "scene": "门口", + "source_id": "smartbench_0217", + "source_url": "https://www.youtube.com/watch?v=jNsO1K0mRwI", + "duration_s": 7.007, + "file": "clips/S28.mp4" + }, + { + "clip_id": "S29", + "title": "狗打开柜门并拉扯垃圾袋", + "scene": "室内", + "source_id": "smartbench_0734", + "source_url": "https://www.youtube.com/watch?v=-82STtPbfEc", + "duration_s": 73.031, + "file": "clips/S29.mp4" + }, + { + "clip_id": "S30", + "title": "人员拿包裹时身体遮挡", + "scene": "门口", + "source_id": "smartbench_0456", + "source_url": "https://www.youtube.com/watch?v=Xl-R3YCQRkY", + "duration_s": 22.022, + "file": "clips/S30.mp4" + }, + { + "clip_id": "S31", + "title": "离家后短暂返回门口", + "scene": "门口", + "source_id": "smartbench_0716", + "source_url": "https://www.youtube.com/watch?v=WRnhem3hsxc", + "duration_s": 15.905, + "file": "clips/S31.mp4" + }, + { + "clip_id": "S32", + "title": "清理桌面并擦拭_表演采集", + "scene": "室内", + "source_id": "charades_6EU06", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 30.696, + "file": "clips/S32.mp4" + }, + { + "clip_id": "S33", + "title": "固定机位车库清扫", + "scene": "室内", + "source_id": "charades_U1DTW", + "source_url": "https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip", + "duration_s": 32.763, + "file": "clips/S33.mp4" + } +] \ No newline at end of file diff --git a/model_runtime.py b/model_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..b39d624d92eadd30d984a68337011c0841fdf25e --- /dev/null +++ b/model_runtime.py @@ -0,0 +1,54 @@ +"""HF-hosted imajev, using the same adapter revision as the verified local app.""" +from pathlib import Path +import base64 +import io +import json +import os +import sys +from time import perf_counter + +ROOT = Path(__file__).resolve().parent +for folder in (ROOT/'upstream/src', ROOT/'upstream/scripts', ROOT/'upstream/scripts/playground'): + sys.path.insert(0, str(folder)) + +def load_model(): + from huggingface_hub import snapshot_download + from server import TorchBackend + from vision_decision.calibration import TemperatureCalibrator + base = snapshot_download('Qwen/Qwen3.5-4B', revision='851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a', allow_patterns=['*.json','*.safetensors','*.txt','*.jinja'], token=False) + adapter = snapshot_download('mohit67890/imajev-4b', revision='f8d8234cebc6c99065c07731e59716dc0a6e27ab', allow_patterns=['*.json','*.safetensors'], ignore_patterns=['mlx/*','assets/*'], token=False) + runtime = Path(os.getenv('HOME_PULSE_DATA_DIR', '/tmp/home-pulse')) + runtime.mkdir(parents=True, exist_ok=True) + bundle = runtime/'model-bundle.json' + bundle.write_text(json.dumps({'path':base})) + # ZeroGPU emulates CUDA at module startup and materializes it inside spaces.GPU. + backend = TorchBackend(bundle=bundle, adapter=Path(adapter), device='cuda', rotations=1, max_input_tokens=4096, fast=False, merge_lora=False) + backend.model = 'imajev-4b-hf-bf16' + backend.engine.processor._vision() + calibration = TemperatureCalibrator.load(Path(adapter)/'calibration.json') + return backend, calibration + +def predict(backend, calibration, payload): + from PIL import Image + import torch + from server import compile_payload + from vision_decision.jev_api import to_response + start=perf_counter() + supplied=payload.get('images',[]) + if not 1<=len(supplied)<=2: raise ValueError('Provide one or two images') + images=[] + for value in supplied: + if not isinstance(value,str) or not value.startswith('data:image/') or ';base64,' not in value: raise ValueError('Invalid image') + blob=base64.b64decode(value.split(',',1)[1],validate=True) + if len(blob)>3_000_000: raise ValueError('Image too large') + with Image.open(io.BytesIO(blob)) as original: + if original.width*original.height>16_000_000: raise ValueError('Image dimensions too large') + image=original.convert('RGB');image.thumbnail((640,640));images.append(image) + if not 1<=len(payload.get('questions',{}))<=4: raise ValueError('Provide 1–4 questions') + request, plan=compile_payload({k:v for k,v in payload.items() if k not in ('images','model','thinking')},backend.max_options) + with torch.inference_mode(): results,usage=backend.score(images,request) + torch.cuda.synchronize() + results=[calibration.calibrate_result(result,field.type,len(result.scores)-1,image=True,photo_only=not request.state) for field,result in zip(request.fields,results)] + response=to_response(request,results,model=backend.model,plan=plan) + response['usage']={**usage,'total_ms':round((perf_counter()-start)*1000,1),'processed_image_sizes':[list(im.size) for im in images]} + return response diff --git a/q_align/__init__.py b/q_align/__init__.py deleted file mode 100644 index c0e4234303e2ad423b55342b0000d9dfc5b88df3..0000000000000000000000000000000000000000 --- a/q_align/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .model import MPLUGOwl2LlamaForCausalLM \ No newline at end of file diff --git a/q_align/__pycache__/__init__.cpython-310.pyc b/q_align/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index a7db7c91534d4d9fcba53458c73de8b7b93319c0..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/q_align/__pycache__/__init__.cpython-311.pyc b/q_align/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index 43eabac5150ca8ac52e0fe20c593ea49d166b30c..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/q_align/__pycache__/__init__.cpython-39.pyc b/q_align/__pycache__/__init__.cpython-39.pyc deleted file mode 100644 index 9711d49034200f623d0a4231eca427b704a13af9..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/__init__.cpython-39.pyc and /dev/null differ diff --git a/q_align/__pycache__/constants.cpython-310.pyc b/q_align/__pycache__/constants.cpython-310.pyc deleted file mode 100644 index 40d379600f04196fc4637597294b0a48dd6c4edc..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/constants.cpython-310.pyc and /dev/null differ diff --git a/q_align/__pycache__/constants.cpython-311.pyc b/q_align/__pycache__/constants.cpython-311.pyc deleted file mode 100644 index ed26139984658aa167829ebb17321ac8eabb7f79..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/constants.cpython-311.pyc and /dev/null differ diff --git a/q_align/__pycache__/constants.cpython-39.pyc b/q_align/__pycache__/constants.cpython-39.pyc deleted file mode 100644 index a78884864b830cccdb26eb71c54b6f74944533e5..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/constants.cpython-39.pyc and /dev/null differ diff --git a/q_align/__pycache__/conversation.cpython-310.pyc b/q_align/__pycache__/conversation.cpython-310.pyc deleted file mode 100644 index 0e3817f60cf760318094a82981eb13d9f39b975d..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/conversation.cpython-310.pyc and /dev/null differ diff --git a/q_align/__pycache__/conversation.cpython-311.pyc b/q_align/__pycache__/conversation.cpython-311.pyc deleted file mode 100644 index 570ae579548d6bcbe60e21df289d19c68aa03644..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/conversation.cpython-311.pyc and /dev/null differ diff --git a/q_align/__pycache__/conversation.cpython-39.pyc b/q_align/__pycache__/conversation.cpython-39.pyc deleted file mode 100644 index 29aa67455004b8251e5a63a880ff144831a37a87..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/conversation.cpython-39.pyc and /dev/null differ diff --git a/q_align/__pycache__/mm_utils.cpython-310.pyc b/q_align/__pycache__/mm_utils.cpython-310.pyc deleted file mode 100644 index 519d0457d58e50de78d109b3004e2464a6d67d2c..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/mm_utils.cpython-310.pyc and /dev/null differ diff --git a/q_align/__pycache__/mm_utils.cpython-311.pyc b/q_align/__pycache__/mm_utils.cpython-311.pyc deleted file mode 100644 index 47702f8c81d7079d18936516385cc5a4ddad53bb..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/mm_utils.cpython-311.pyc and /dev/null differ diff --git a/q_align/__pycache__/mm_utils.cpython-39.pyc b/q_align/__pycache__/mm_utils.cpython-39.pyc deleted file mode 100644 index a14b149ddd57f0c91444b14f6719c28b8bac6b9f..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/mm_utils.cpython-39.pyc and /dev/null differ diff --git a/q_align/__pycache__/utils.cpython-311.pyc b/q_align/__pycache__/utils.cpython-311.pyc deleted file mode 100644 index abd682a6a83a001bf72d71cd273b0272972fb6c7..0000000000000000000000000000000000000000 Binary files a/q_align/__pycache__/utils.cpython-311.pyc and /dev/null differ diff --git a/q_align/constants.py b/q_align/constants.py deleted file mode 100644 index b632a10f2c053c72fae8d61a1fa10fa52aa0f4e8..0000000000000000000000000000000000000000 --- a/q_align/constants.py +++ /dev/null @@ -1,9 +0,0 @@ -CONTROLLER_HEART_BEAT_EXPIRATION = 30 -WORKER_HEART_BEAT_INTERVAL = 15 - -LOGDIR = "./demo_logs" - -# Model Constants -IGNORE_INDEX = -100 -IMAGE_TOKEN_INDEX = -200 -DEFAULT_IMAGE_TOKEN = "<|image|>" diff --git a/q_align/conversation.py b/q_align/conversation.py deleted file mode 100644 index e9f6f3f518f8b4426493ff7dacb0f6b70ae56c09..0000000000000000000000000000000000000000 --- a/q_align/conversation.py +++ /dev/null @@ -1,301 +0,0 @@ -import dataclasses -from enum import auto, Enum -from typing import List, Tuple -from q_align.constants import DEFAULT_IMAGE_TOKEN - -class SeparatorStyle(Enum): - """Different separator style.""" - SINGLE = auto() - TWO = auto() - TWO_NO_SYS = auto() - MPT = auto() - PLAIN = auto() - LLAMA_2 = auto() - - -@dataclasses.dataclass -class Conversation: - """A class that keeps all conversation history.""" - system: str - roles: List[str] - messages: List[List[str]] - offset: int - sep_style: SeparatorStyle = SeparatorStyle.SINGLE - sep: str = "###" - sep2: str = None - version: str = "Unknown" - - skip_next: bool = False - - def get_prompt(self): - messages = self.messages - if len(messages) > 0 and type(messages[0][1]) is tuple: - messages = self.messages.copy() - init_role, init_msg = messages[0].copy() - # init_msg = init_msg[0].replace("", "").strip() - # if 'mmtag' in self.version: - # messages[0] = (init_role, init_msg) - # messages.insert(0, (self.roles[0], "")) - # messages.insert(1, (self.roles[1], "Received.")) - # else: - # messages[0] = (init_role, "\n" + init_msg) - init_msg = init_msg[0].replace(DEFAULT_IMAGE_TOKEN, "").strip() - messages[0] = (init_role, DEFAULT_IMAGE_TOKEN + init_msg) - - if self.sep_style == SeparatorStyle.SINGLE: - ret = self.system + self.sep - for role, message in messages: - if message: - if type(message) is tuple: - message, _, _ = message - ret += role + ": " + message + self.sep - else: - ret += role + ":" - elif self.sep_style == SeparatorStyle.TWO: - seps = [self.sep, self.sep2] - ret = self.system + seps[0] - for i, (role, message) in enumerate(messages): - if message: - if type(message) is tuple: - message, _, _ = message - ret += role + ": " + message + seps[i % 2] - else: - ret += role + ":" - elif self.sep_style == SeparatorStyle.TWO_NO_SYS: - seps = [self.sep, self.sep2] - ret = "" - for i, (role, message) in enumerate(messages): - if message: - if type(message) is tuple: - message, _, _ = message - ret += role + ": " + message + seps[i % 2] - else: - ret += role + ":" - elif self.sep_style == SeparatorStyle.MPT: - ret = self.system + self.sep - for role, message in messages: - if message: - if type(message) is tuple: - message, _, _ = message - ret += role + message + self.sep - else: - ret += role - elif self.sep_style == SeparatorStyle.LLAMA_2: - wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" - wrap_inst = lambda msg: f"[INST] {msg} [/INST]" - ret = "" - - for i, (role, message) in enumerate(messages): - if i == 0: - assert message, "first message should not be none" - assert role == self.roles[0], "first message should come from user" - if message: - if type(message) is tuple: - message, _, _ = message - if i == 0: message = wrap_sys(self.system) + message - if i % 2 == 0: - message = wrap_inst(message) - ret += self.sep + message - else: - ret += " " + message + " " + self.sep2 - else: - ret += "" - ret = ret.lstrip(self.sep) - elif self.sep_style == SeparatorStyle.PLAIN: - seps = [self.sep, self.sep2] - ret = self.system - for i, (role, message) in enumerate(messages): - if message: - if type(message) is tuple: - message, _, _ = message - ret += message + seps[i % 2] - else: - ret += "" - else: - raise ValueError(f"Invalid style: {self.sep_style}") - - return ret - - def append_message(self, role, message): - self.messages.append([role, message]) - - def get_images(self, return_pil=False): - images = [] - for i, (role, msg) in enumerate(self.messages[self.offset:]): - if i % 2 == 0: - if type(msg) is tuple: - import base64 - from io import BytesIO - from PIL import Image - msg, image, image_process_mode = msg - if image_process_mode == "Pad": - def expand2square(pil_img, background_color=(122, 116, 104)): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - image = expand2square(image) - elif image_process_mode in ["Default", "Crop"]: - pass - elif image_process_mode == "Resize": - image = image.resize((336, 336)) - else: - raise ValueError(f"Invalid image_process_mode: {image_process_mode}") - max_hw, min_hw = max(image.size), min(image.size) - aspect_ratio = max_hw / min_hw - max_len, min_len = 800, 400 - shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) - longest_edge = int(shortest_edge * aspect_ratio) - W, H = image.size - if longest_edge != max(image.size): - if H > W: - H, W = longest_edge, shortest_edge - else: - H, W = shortest_edge, longest_edge - image = image.resize((W, H)) - if return_pil: - images.append(image) - else: - buffered = BytesIO() - image.save(buffered, format="PNG") - img_b64_str = base64.b64encode(buffered.getvalue()).decode() - images.append(img_b64_str) - return images - - def to_gradio_chatbot(self): - ret = [] - for i, (role, msg) in enumerate(self.messages[self.offset:]): - if i % 2 == 0: - if type(msg) is tuple: - import base64 - from io import BytesIO - msg, image, image_process_mode = msg - max_hw, min_hw = max(image.size), min(image.size) - aspect_ratio = max_hw / min_hw - max_len, min_len = 800, 400 - shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) - longest_edge = int(shortest_edge * aspect_ratio) - W, H = image.size - if H > W: - H, W = longest_edge, shortest_edge - else: - H, W = shortest_edge, longest_edge - image = image.resize((W, H)) - buffered = BytesIO() - image.save(buffered, format="JPEG") - img_b64_str = base64.b64encode(buffered.getvalue()).decode() - img_str = f'user upload image' - msg = img_str + msg.replace('<|image|>', '').strip() - ret.append([msg, None]) - else: - ret.append([msg, None]) - else: - ret[-1][-1] = msg - return ret - - def copy(self): - return Conversation( - system=self.system, - roles=self.roles, - messages=[[x, y] for x, y in self.messages], - offset=self.offset, - sep_style=self.sep_style, - sep=self.sep, - sep2=self.sep2, - version=self.version) - - def dict(self): - if len(self.get_images()) > 0: - return { - "system": self.system, - "roles": self.roles, - "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages], - "offset": self.offset, - "sep": self.sep, - "sep2": self.sep2, - } - return { - "system": self.system, - "roles": self.roles, - "messages": self.messages, - "offset": self.offset, - "sep": self.sep, - "sep2": self.sep2, - } - - -conv_vicuna_v0 = Conversation( - system="A chat between a curious human and an artificial intelligence assistant. " - "The assistant gives helpful, detailed, and polite answers to the human's questions.", - roles=("Human", "Assistant"), - messages=( - ("Human", "What are the key differences between renewable and non-renewable energy sources?"), - ("Assistant", - "Renewable energy sources are those that can be replenished naturally in a relatively " - "short amount of time, such as solar, wind, hydro, geothermal, and biomass. " - "Non-renewable energy sources, on the other hand, are finite and will eventually be " - "depleted, such as coal, oil, and natural gas. Here are some key differences between " - "renewable and non-renewable energy sources:\n" - "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable " - "energy sources are finite and will eventually run out.\n" - "2. Environmental impact: Renewable energy sources have a much lower environmental impact " - "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, " - "and other negative effects.\n" - "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically " - "have lower operational costs than non-renewable sources.\n" - "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote " - "locations than non-renewable sources.\n" - "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different " - "situations and needs, while non-renewable sources are more rigid and inflexible.\n" - "6. Sustainability: Renewable energy sources are more sustainable over the long term, while " - "non-renewable sources are not, and their depletion can lead to economic and social instability.\n") - ), - offset=2, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) - -conv_vicuna_v1 = Conversation( - system="A chat between a curious user and an artificial intelligence assistant. " - "The assistant gives helpful, detailed, and polite answers to the user's questions.", - roles=("USER", "ASSISTANT"), - version="v1", - messages=(), - offset=0, - sep_style=SeparatorStyle.TWO, - sep=" ", - sep2="", -) - -conv_mplug_owl2 = Conversation( - system="A chat between a curious human and an artificial intelligence assistant. " - "The assistant gives helpful, detailed, and polite answers to the human's questions.", - roles=("USER", "ASSISTANT"), - version="v1", - messages=(), - offset=0, - sep_style=SeparatorStyle.TWO_NO_SYS, - sep=" ", - sep2="", -) - -# default_conversation = conv_vicuna_v1 -default_conversation = conv_mplug_owl2 -conv_templates = { - "default": conv_vicuna_v0, - "v0": conv_vicuna_v0, - "v1": conv_vicuna_v1, - "vicuna_v1": conv_vicuna_v1, - "mplug_owl2": conv_mplug_owl2, -} - - -if __name__ == "__main__": - print(default_conversation.get_prompt()) \ No newline at end of file diff --git a/q_align/evaluate/__pycache__/scorer.cpython-311.pyc b/q_align/evaluate/__pycache__/scorer.cpython-311.pyc deleted file mode 100644 index b421b86aed039452e511142014200bb403f9e659..0000000000000000000000000000000000000000 Binary files a/q_align/evaluate/__pycache__/scorer.cpython-311.pyc and /dev/null differ diff --git a/q_align/evaluate/eval.py b/q_align/evaluate/eval.py deleted file mode 100644 index 008b7b07abfec6c41a1162a582dae2ccdae5f597..0000000000000000000000000000000000000000 --- a/q_align/evaluate/eval.py +++ /dev/null @@ -1,138 +0,0 @@ -import argparse -import torch - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.conversation import conv_templates, SeparatorStyle -from q_align.model.builder import load_pretrained_model -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -from PIL import Image - -import requests -from PIL import Image -from io import BytesIO -from transformers import TextStreamer - -import json -from tqdm import tqdm -from collections import defaultdict - -import os - - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def load_image(image_file): - if image_file.startswith('http://') or image_file.startswith('https://'): - response = requests.get(image_file) - image = Image.open(BytesIO(response.content)).convert('RGB') - else: - image = Image.open(image_file).convert('RGB') - return image - - -def main(args): - # Model - disable_torch_init() - - model_name = get_model_name_from_path(args.model_path) - tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) - - - import json - - - image_path = "playground/data/" - - json_prefix = "playground/data/labels/mos_simple/" - jsons = [ - json_prefix + "test_flive.json", - json_prefix + "combined/kadid_ref.json", - json_prefix + "combined/livec.json", - json_prefix + "test_koniq.json", - json_prefix + "test_spaq.json", - json_prefix + "combined/agi.json", - json_prefix + "combined/kadid.json", - ] - - os.makedirs(f"results/{args.model_path}/", exist_ok=True) - - - conv_mode = "mplug_owl2" - - inp = "How would you rate the quality of this image?" - - conv = conv_templates[conv_mode].copy() - inp = inp + "\n" + DEFAULT_IMAGE_TOKEN - conv.append_message(conv.roles[0], inp) - image = None - - conv.append_message(conv.roles[1], None) - prompt = conv.get_prompt() + " The quality of the image is" - - toks = ["good", "poor", "high", "fair", "low", "excellent", "bad", "fine", "moderate", "decent", "average", "medium", "acceptable"] - print(toks) - ids_ = [id_[1] for id_ in tokenizer(toks)["input_ids"]] - print(ids_) - - input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() - - for json_ in jsons: - with open(json_) as f: - iqadata = json.load(f) - - image_tensors = [] - batch_data = [] - - for i, llddata in enumerate(tqdm(iqadata, desc="Evaluating [{}]".format(json_.split("/")[-1]))): - #print(f"Evaluating image {i}") - #print(prompt) - filename = llddata["image"] - llddata["logits"] = defaultdict(float) - - image = load_image(image_path + filename) - image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda() - - image_tensors.append(image_tensor) - batch_data.append(llddata) - - if i % 8 == 7 or i == len(iqadata) - 1: - with torch.inference_mode(): - output_logits = model(input_ids.repeat(len(image_tensors), 1), - images=torch.cat(image_tensors, 0))["logits"][:,-1] - - for j, xllddata in enumerate(batch_data): - for tok, id_ in zip(toks, ids_): - xllddata["logits"][tok] += output_logits[j,id_].item() - # print(llddata) - json_ = json_.replace("combined/", "combined-") - # print(f"results/mix-mplug-owl-2-boost_iqa_wu_v2/{json_.split('/')[-1]}") - with open(f"results/{args.model_path}/{json_.split('/')[-1]}", "a") as wf: - json.dump(xllddata, wf) - - image_tensors = [] - batch_data = [] - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/q-align-koniq-spaq-v0") - parser.add_argument("--model-base", type=str, default=None) - parser.add_argument("--device", type=str, default="cuda") - parser.add_argument("--conv-mode", type=str, default=None) - parser.add_argument("--temperature", type=float, default=0.2) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--load-8bit", action="store_true") - parser.add_argument("--load-4bit", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("--image-aspect-ratio", type=str, default='pad') - args = parser.parse_args() - main(args) \ No newline at end of file diff --git a/q_align/evaluate/iaa_eval.py b/q_align/evaluate/iaa_eval.py deleted file mode 100644 index 64f17e29dacae2c145c0b10d1fe0dcdc27b8f6b9..0000000000000000000000000000000000000000 --- a/q_align/evaluate/iaa_eval.py +++ /dev/null @@ -1,164 +0,0 @@ -import argparse -import torch - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.conversation import conv_templates, SeparatorStyle -from q_align.model.builder import load_pretrained_model -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -from PIL import Image -from PIL import ImageFile -ImageFile.LOAD_TRUNCATED_IMAGES = True - -import requests -from PIL import Image -from io import BytesIO -from transformers import TextStreamer - -from scipy.stats import spearmanr, pearsonr - - -import json -from tqdm import tqdm -from collections import defaultdict - -import os - -def wa5(logits): - import numpy as np - logprobs = np.array([logits["excellent"], logits["good"], logits["fair"], logits["poor"], logits["bad"]]) - probs = np.exp(logprobs) / np.sum(np.exp(logprobs)) - return np.inner(probs, np.array([1,0.75,0.5,0.25,0.])) - - - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def load_image(image_file): - if image_file.startswith('http://') or image_file.startswith('https://'): - response = requests.get(image_file) - image = Image.open(BytesIO(response.content)).convert('RGB') - else: - image = Image.open(image_file).convert('RGB') - return image - - -def main(args): - # Model - disable_torch_init() - - model_name = get_model_name_from_path(args.model_path) - tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) - - - import json - - - image_path = "playground/data/" - - - json_prefix = "playground/data/test_jsons/" - jsons = [ - json_prefix + "test_ava.json", - ] - - os.makedirs(f"results/{args.model_path}/", exist_ok=True) - - - conv_mode = "mplug_owl2" - - inp = "How would you rate the aesthetics of this image?" - - conv = conv_templates[conv_mode].copy() - inp = DEFAULT_IMAGE_TOKEN + inp - conv.append_message(conv.roles[0], inp) - image = None - - conv.append_message(conv.roles[1], None) - prompt = conv.get_prompt() + " The aesthetics of the image is" - - toks = ["good", "poor", "high", "fair", "low", "excellent", "bad", "fine", "moderate", "decent", "average", "medium", "acceptable"] - print(toks) - ids_ = [id_[1] for id_ in tokenizer(toks)["input_ids"]] - print(ids_) - - input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(args.device) - - for json_ in jsons: - with open(json_) as f: - iqadata = json.load(f) - - image_tensors = [] - batch_data = [] - prs, gts = [], [] - for i, llddata in enumerate(tqdm(iqadata, desc="Evaluating [{}]".format(json_.split("/")[-1]))): - filename = llddata["image"] - llddata["logits"] = defaultdict(float) - - - - image = load_image(image_path + filename) - def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean)) - image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().to(args.device) - - image_tensors.append(image_tensor) - batch_data.append(llddata) - - if i % 8 == 7 or i == len(iqadata) - 1: - with torch.inference_mode(): - output_logits = model(input_ids.repeat(len(image_tensors), 1), - images=torch.cat(image_tensors, 0))["logits"][:,-1] - - for j, xllddata in enumerate(batch_data): - for tok, id_ in zip(toks, ids_): - xllddata["logits"][tok] += output_logits[j,id_].item() - xllddata["score"] = wa5(xllddata["logits"]) - # print(llddata) - prs.append(xllddata["score"]) - gts.append(xllddata["gt_score"]) - json_ = json_.replace("combined/", "combined-") - with open(f"results/{args.model_path}/{json_.split('/')[-1]}", "a") as wf: - json.dump(xllddata, wf) - - image_tensors = [] - batch_data = [] - - #if i > 0 and i % 200 == 0: - # print(spearmanr(prs,gts)[0], pearsonr(prs,gts)[0]) - print("Spearmanr", spearmanr(prs,gts)[0], "Pearson", pearsonr(prs,gts)[0]) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/one-align") - parser.add_argument("--model-base", type=str, default=None) - parser.add_argument("--device", type=str, default="cuda:0") - parser.add_argument("--conv-mode", type=str, default=None) - parser.add_argument("--temperature", type=float, default=0.2) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--load-8bit", action="store_true") - parser.add_argument("--load-4bit", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("--image-aspect-ratio", type=str, default='pad') - args = parser.parse_args() - main(args) \ No newline at end of file diff --git a/q_align/evaluate/iqa4vqa_eval.py b/q_align/evaluate/iqa4vqa_eval.py deleted file mode 100644 index 1aaf1a7ac9ec4ee21a48ee96bfc92fe742559c24..0000000000000000000000000000000000000000 --- a/q_align/evaluate/iqa4vqa_eval.py +++ /dev/null @@ -1,150 +0,0 @@ -import argparse -import torch - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.conversation import conv_templates, SeparatorStyle -from q_align.model.builder import load_pretrained_model -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -from PIL import Image - -import requests -from PIL import Image -from io import BytesIO -from transformers import TextStreamer - -from decord import VideoReader - - -import json -from tqdm import tqdm -from collections import defaultdict - -import os - - - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def load_video(video_file): - vr = VideoReader(video_file) - - # Get video frame rate - fps = vr.get_avg_fps() - - # Calculate frame indices for 1fps - frame_indices = [int(fps * i) for i in range(int(len(vr) / fps))] - frames = vr.get_batch(frame_indices).asnumpy() - return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))] - - -def main(args): - # Model - disable_torch_init() - - model_name = get_model_name_from_path(args.model_path) - tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) - - - import json - - - image_paths = [ - "playground/data/", - "playground/data/", - "playground/data/KoNViD_1k_videos/", - "playground/data/maxwell/", - ] - - json_prefix = "playground/data/test_jsons/" - jsons = [ - json_prefix + "test_lsvq.json", - json_prefix + "test_lsvq_1080p.json", - json_prefix + "konvid.json", - json_prefix + "maxwell_test.json", - ] - - os.makedirs(f"results/{args.model_path}/", exist_ok=True) - - - conv_mode = "mplug_owl2" - - inp = "How would you rate the quality of this image?" - - conv = conv_templates[conv_mode].copy() - inp = inp + "\n" + DEFAULT_IMAGE_TOKEN - conv.append_message(conv.roles[0], inp) - image = None - - conv.append_message(conv.roles[1], None) - prompt = conv.get_prompt() + " The quality of the image is" - - toks = ["good", "poor", "high", "fair", "low", "excellent", "bad", "fine", "moderate", "decent", "average", "medium", "acceptable"] - print(toks) - ids_ = [id_[1] for id_ in tokenizer(toks)["input_ids"]] - print(ids_) - - input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(args.device) - - for image_path, json_ in zip(image_paths, jsons): - with open(json_) as f: - iqadata = json.load(f) - try: - for i, llddata in enumerate(tqdm(iqadata, desc="Evaluating [{}]".format(json_.split("/")[-1]))): - filename = llddata["img_path"] - llddata["logits"] = defaultdict(float) - - image = load_video(image_path + filename) - def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - image = [expand2square(img, tuple(int(x*255) for x in image_processor.image_mean)) for img in image] - image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().to(args.device) - - - if True: - with torch.inference_mode(): - output_logits = model(input_ids.repeat(image_tensor.shape[0], 1), - images=image_tensor)["logits"][:,-1] - - for tok, id_ in zip(toks, ids_): - llddata["logits"][tok] += output_logits.mean(0)[id_].item() - # print(llddata) - json_ = json_.replace("combined/", "combined-") - with open(f"results/{args.model_path}/{json_.split('/')[-1]}", "a") as wf: - json.dump(llddata, wf) - except: - continue - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/q-align-image") - parser.add_argument("--model-base", type=str, default=None) - parser.add_argument("--device", type=str, default="cuda:0") - parser.add_argument("--conv-mode", type=str, default=None) - parser.add_argument("--temperature", type=float, default=0.2) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--load-8bit", action="store_true") - parser.add_argument("--load-4bit", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("--image-aspect-ratio", type=str, default='pad') - args = parser.parse_args() - main(args) \ No newline at end of file diff --git a/q_align/evaluate/iqa_eval.py b/q_align/evaluate/iqa_eval.py deleted file mode 100644 index 3e0695d696cdad4b277aab3a753dc4b9dce89af1..0000000000000000000000000000000000000000 --- a/q_align/evaluate/iqa_eval.py +++ /dev/null @@ -1,156 +0,0 @@ -import argparse -import torch - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.conversation import conv_templates, SeparatorStyle -from q_align.model.builder import load_pretrained_model -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -from PIL import Image - -import requests -from PIL import Image -from io import BytesIO -from transformers import TextStreamer - -import json -from tqdm import tqdm -from collections import defaultdict - -import os - - - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def load_image(image_file): - if image_file.startswith('http://') or image_file.startswith('https://'): - response = requests.get(image_file) - image = Image.open(BytesIO(response.content)).convert('RGB') - else: - image = Image.open(image_file).convert('RGB') - return image - - -def main(args): - # Model - disable_torch_init() - - model_name = get_model_name_from_path(args.model_path) - tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) - - - import json - - - image_path = "playground/data/" - - - json_prefix = "playground/data/test_jsons/" - jsons = [ - json_prefix + "test_imagerewarddb.json", - json_prefix + "test_koniq.json", - json_prefix + "test_spaq.json", - json_prefix + "test_kadid.json", - json_prefix + "livec.json", - json_prefix + "agi.json", - json_prefix + "live.json", - json_prefix + "csiq.json", - ] - - os.makedirs(f"results/{args.model_path}/", exist_ok=True) - - - conv_mode = "mplug_owl2" - - inp = "Evaluate the image quality of the following image."#"How would you rate the quality of this image?" - - conv = conv_templates[conv_mode].copy() - inp = inp + "\n" + DEFAULT_IMAGE_TOKEN - conv.append_message(conv.roles[0], inp) - image = None - - conv.append_message(conv.roles[1], None) - prompt = conv.get_prompt() + " The quality of the image is" - - toks = ["good", "poor", "high", "fair", "low", "excellent", "bad", "fine", "moderate", "decent", "average", "medium", "acceptable"] - print(toks) - ids_ = [id_[1] for id_ in tokenizer(toks)["input_ids"]] - print(ids_) - - input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(args.device) - - for json_ in jsons: - with open(json_) as f: - iqadata = json.load(f) - - image_tensors = [] - batch_data = [] - - for i, llddata in enumerate(tqdm(iqadata, desc="Evaluating [{}]".format(json_.split("/")[-1]))): - if True: - try: - filename = llddata["image"] - except: - filename = llddata["img_path"] - llddata["logits"] = defaultdict(float) - - image = load_image(image_path + filename) - def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean)) - image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().to(args.device) - - image_tensors.append(image_tensor) - batch_data.append(llddata) - - if i % 8 == 7 or i == len(iqadata) - 1: - with torch.inference_mode(): - output_logits = model(input_ids.repeat(len(image_tensors), 1), - images=torch.cat(image_tensors, 0))["logits"][:,-1] - - for j, xllddata in enumerate(batch_data): - for tok, id_ in zip(toks, ids_): - xllddata["logits"][tok] += output_logits[j,id_].item() - # print(llddata) - json_ = json_.replace("combined/", "combined-") - with open(f"results/{args.model_path}/2{json_.split('/')[-1]}", "a") as wf: - json.dump(xllddata, wf) - - image_tensors = [] - batch_data = [] - - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/one-align") - parser.add_argument("--model-base", type=str, default=None) - parser.add_argument("--device", type=str, default="cuda:0") - parser.add_argument("--conv-mode", type=str, default=None) - parser.add_argument("--temperature", type=float, default=0.2) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--load-8bit", action="store_true") - parser.add_argument("--load-4bit", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("--image-aspect-ratio", type=str, default='pad') - args = parser.parse_args() - main(args) \ No newline at end of file diff --git a/q_align/evaluate/scorer.py b/q_align/evaluate/scorer.py deleted file mode 100644 index 4d68f83df09a0f8696a49bede9844d7e7d6465dd..0000000000000000000000000000000000000000 --- a/q_align/evaluate/scorer.py +++ /dev/null @@ -1,155 +0,0 @@ -from PIL import Image - -import torch.nn as nn -import torch - -from typing import List - -from q_align.model.builder import load_pretrained_model - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -def load_video(video_file): - from decord import VideoReader - vr = VideoReader(video_file) - - # Get video frame rate - fps = vr.get_avg_fps() - - # Calculate frame indices for 1fps - frame_indices = [int(fps * i) for i in range(int(len(vr) / fps))] - frames = vr.get_batch(frame_indices).asnumpy() - return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))] - - -class QAlignScorer(nn.Module): - def __init__(self, pretrained="q-future/one-align", device="cuda:0", tokenizer=None, model=None, image_processor=None): - super().__init__() - if model is None: - tokenizer, model, image_processor, _ = load_pretrained_model(pretrained, None, "mplug_owl2", device=device) - prompt = "USER: How would you rate the quality of this image?\n<|image|>\nASSISTANT: The quality of the image is" - - self.preferential_ids_ = [id_[1] for id_ in tokenizer(["excellent","good","fair","poor","bad"])["input_ids"]] - self.weight_tensor = torch.Tensor([1,0.75,0.5,0.25,0.]).half().to(model.device) - - self.tokenizer = tokenizer - self.model = model - self.image_processor = image_processor - self.input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device) - - def expand2square(self, pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - - def forward(self, image: List[Image.Image]): - image = [self.expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in image] - with torch.inference_mode(): - image_tensor = self.image_processor.preprocess(image, return_tensors="pt")["pixel_values"].half().to(self.model.device) - output_logits = self.model(self.input_ids.repeat(image_tensor.shape[0], 1), - images=image_tensor)["logits"][:,-1, self.preferential_ids_] - - return torch.softmax(output_logits, -1) #@ self.weight_tensor - - -class QAlignAestheticScorer(nn.Module): - def __init__(self, pretrained="q-future/one-align", device="cuda:0", tokenizer=None, model=None, image_processor=None): - super().__init__() - if model is None: - tokenizer, model, image_processor, _ = load_pretrained_model(pretrained, None, "mplug_owl2", device=device) - prompt = "USER: How would you rate the aesthetics of this image?\n<|image|>\nASSISTANT: The aesthetics of the image is" - - self.preferential_ids_ = [id_[1] for id_ in tokenizer(["excellent","good","fair","poor","bad"])["input_ids"]] - self.weight_tensor = torch.Tensor([1,0.75,0.5,0.25,0.]).half().to(model.device) - - self.tokenizer = tokenizer - self.model = model - self.image_processor = image_processor - self.input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device) - - def expand2square(self, pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - - def forward(self, image: List[Image.Image]): - image = [self.expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in image] - with torch.inference_mode(): - image_tensor = self.image_processor.preprocess(image, return_tensors="pt")["pixel_values"].half().to(self.model.device) - output_logits = self.model(self.input_ids.repeat(image_tensor.shape[0], 1), - images=image_tensor)["logits"][:,-1, self.preferential_ids_] - - return torch.softmax(output_logits, -1) #@ self.weight_tensor - -class QAlignVideoScorer(nn.Module): - def __init__(self, pretrained="q-future/one-align", device="cuda:0", tokenizer=None, model=None, image_processor=None): - super().__init__() - if model is None: - tokenizer, model, image_processor, _ = load_pretrained_model(pretrained, None, "mplug_owl2", device=device) - prompt = "USER: How would you rate the quality of this video?\n<|image|>\nASSISTANT: The quality of the video is" - - self.preferential_ids_ = [id_[1] for id_ in tokenizer(["excellent","good","fair","poor","bad"])["input_ids"]] - self.weight_tensor = torch.Tensor([1,0.75,0.5,0.25,0.]).half().to(model.device) - - self.tokenizer = tokenizer - self.model = model - self.image_processor = image_processor - self.input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device) - - def expand2square(self, pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - - def forward(self, video: List[List[Image.Image]]): - video = [[self.expand2square(frame, tuple(int(x*255) for x in self.image_processor.image_mean)) for frame in vid] for vid in video] - with torch.inference_mode(): - video_tensors = [self.image_processor.preprocess(vid, return_tensors="pt")["pixel_values"].half().to(self.model.device) for vid in video] - output_logits = self.model(self.input_ids.repeat(len(video_tensors), 1), - images=video_tensors)["logits"][:,-1, self.preferential_ids_] - return torch.softmax(output_logits, -1) #@ self.weight_tensor - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/one-align") - parser.add_argument("--device", type=str, default="cuda:0") - parser.add_argument("--img_path", type=str, default="fig/singapore_flyer.jpg") - parser.add_argument("--aesthetic", action="store_true") - parser.add_argument("--video", action="store_true") - args = parser.parse_args() - - if args.video: - scorer = QAlignVideoScorer(pretrained=args.model_path, device=args.device) - print(scorer([load_video(args.img_path)]).tolist()) - else: - scorer = QAlignScorer(pretrained=args.model_path, device=args.device) if not args.aesthetic else QAlignAestheticScorer(pretrained=args.model_path, device=args.device) - print(scorer([Image.open(args.img_path)]).tolist()) - diff --git a/q_align/evaluate/vqa_eval.py b/q_align/evaluate/vqa_eval.py deleted file mode 100644 index 7cb69fea96cf97ed9fd41554460026f0caa34614..0000000000000000000000000000000000000000 --- a/q_align/evaluate/vqa_eval.py +++ /dev/null @@ -1,167 +0,0 @@ -import argparse -import torch - -from q_align.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN -from q_align.conversation import conv_templates, SeparatorStyle -from q_align.model.builder import load_pretrained_model -from q_align.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria - -from PIL import Image - -import requests -from PIL import Image -from io import BytesIO -from transformers import TextStreamer - - -from scipy.stats import spearmanr, pearsonr - -import json -from tqdm import tqdm -from collections import defaultdict - -import os - -def wa5(logits): - import numpy as np - logprobs = np.array([logits["excellent"], logits["good"], logits["fair"], logits["poor"], logits["bad"]]) - probs = np.exp(logprobs) / np.sum(np.exp(logprobs)) - return np.inner(probs, np.array([1,0.75,0.5,0.25,0.])) - - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def load_video(video_file): - from decord import VideoReader - vr = VideoReader(video_file) - - # Get video frame rate - fps = vr.get_avg_fps() - - # Calculate frame indices for 1fps - frame_indices = [int(fps * i) for i in range(int(len(vr) / fps))] - frames = vr.get_batch(frame_indices).asnumpy() - return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))] - - -def main(args): - # Model - disable_torch_init() - - model_name = get_model_name_from_path(args.model_path) - tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device) - - - import json - - - image_paths = [ - #"playground/data/", - #"playground/data/", - "playground/data/KoNViD_1k_videos/", - "playground/data/maxwell/", - - ] - - json_prefix = "playground/data/test_jsons/" - jsons = [ - #json_prefix + "test_lsvq.json", - #json_prefix + "test_lsvq_1080p.json", - json_prefix + "konvid.json", - json_prefix + "maxwell_test.json", - ] - - os.makedirs(f"results/{args.model_path}/", exist_ok=True) - - - conv_mode = "mplug_owl2" - - inp = "How would you rate the quality of this video?" - - conv = conv_templates[conv_mode].copy() - inp = inp + "\n" + DEFAULT_IMAGE_TOKEN - conv.append_message(conv.roles[0], inp) - image = None - - conv.append_message(conv.roles[1], None) - prompt = conv.get_prompt() + " The quality of the video is" - - toks = ["good", "poor", "high", "fair", "low", "excellent", "bad", "fine", "moderate", "decent", "average", "medium", "acceptable"] - print(toks) - ids_ = [id_[1] for id_ in tokenizer(toks)["input_ids"]] - print(ids_) - - input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(args.device) - - for image_path, json_ in zip(image_paths, jsons): - with open(json_) as f: - iqadata = json.load(f) - prs, gts = [], [] - for i, llddata in enumerate(tqdm(iqadata, desc="Evaluating [{}]".format(json_.split("/")[-1]))): - try: - try: - filename = llddata["img_path"] - except: - filename = llddata["image"] - llddata["logits"] = defaultdict(float) - - image = load_video(image_path + filename) - def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - image = [expand2square(img, tuple(int(x*255) for x in image_processor.image_mean)) for img in image] - image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().to(args.device) - - if True: - with torch.inference_mode(): - output_logits = model(input_ids, - images=[image_tensor])["logits"][:,-1] - for tok, id_ in zip(toks, ids_): - llddata["logits"][tok] += output_logits.mean(0)[id_].item() - llddata["score"] = wa5(llddata["logits"]) - # print(llddata) - prs.append(llddata["score"]) - gts.append(llddata["gt_score"]) - # print(llddata) - json_ = json_.replace("combined/", "combined-") - with open(f"results/{args.model_path}/2{json_.split('/')[-1]}", "a") as wf: - json.dump(llddata, wf) - - if i > 0 and i % 200 == 0: - print(spearmanr(prs,gts)[0], pearsonr(prs,gts)[0]) - except: - continue - print("Spearmanr", spearmanr(prs,gts)[0], "Pearson", pearsonr(prs,gts)[0]) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--model-path", type=str, default="q-future/one-align") - parser.add_argument("--model-base", type=str, default=None) - parser.add_argument("--device", type=str, default="cuda:0") - parser.add_argument("--conv-mode", type=str, default=None) - parser.add_argument("--temperature", type=float, default=0.2) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--load-8bit", action="store_true") - parser.add_argument("--load-4bit", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("--image-aspect-ratio", type=str, default='pad') - args = parser.parse_args() - main(args) \ No newline at end of file diff --git a/q_align/mm_utils.py b/q_align/mm_utils.py deleted file mode 100644 index ee1ee281029576bf0f23384ebb79a34e2f34d578..0000000000000000000000000000000000000000 --- a/q_align/mm_utils.py +++ /dev/null @@ -1,112 +0,0 @@ -from PIL import Image -from io import BytesIO -import base64 - -import torch -from transformers import StoppingCriteria -from q_align.constants import IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN -from icecream import ic - - -def load_image_from_base64(image): - return Image.open(BytesIO(base64.b64decode(image))) - - -def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - - -def process_images(images, image_processor, model_cfg=None): - if model_cfg is not None: - image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) - else: - image_aspect_ratio = 'resize' - new_images = [] - if image_aspect_ratio == 'pad': - for image in images: - image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean)) - image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] - new_images.append(image) - elif image_aspect_ratio == 'resize': - for image in images: - max_edge = max(image.size) - image = image.resize((max_edge, max_edge)) - image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] - new_images.append(image) - else: - return image_processor(images, return_tensors='pt')['pixel_values'] - if all(x.shape == new_images[0].shape for x in new_images): - new_images = torch.stack(new_images, dim=0) - return new_images - - -def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): - prompt_chunks = [tokenizer(chunk).input_ids if len(chunk) > 0 else [] for chunk in prompt.split(DEFAULT_IMAGE_TOKEN)] - - def insert_separator(X, sep): - return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1] - - input_ids = [] - offset = 0 - if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: - offset = 1 - input_ids.append(prompt_chunks[0][0]) - - for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): - input_ids.extend(x[offset:]) - - if return_tensors is not None: - if return_tensors == 'pt': - return torch.tensor(input_ids, dtype=torch.long) - raise ValueError(f'Unsupported tensor type: {return_tensors}') - return input_ids - - -def get_model_name_from_path(model_path): - model_path = model_path.strip("/") - model_paths = model_path.split("/") - if model_paths[-1].startswith('checkpoint-'): - return model_paths[-2] + "_" + model_paths[-1] - else: - return model_paths[-1] - - - - -class KeywordsStoppingCriteria(StoppingCriteria): - def __init__(self, keywords, tokenizer, input_ids): - self.keywords = keywords - self.keyword_ids = [] - self.max_keyword_len = 0 - for keyword in keywords: - cur_keyword_ids = tokenizer(keyword).input_ids - if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id: - cur_keyword_ids = cur_keyword_ids[1:] - if len(cur_keyword_ids) > self.max_keyword_len: - self.max_keyword_len = len(cur_keyword_ids) - self.keyword_ids.append(torch.tensor(cur_keyword_ids)) - self.tokenizer = tokenizer - self.start_len = input_ids.shape[1] - - def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: - assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO - offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len) - self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids] - for keyword_id in self.keyword_ids: - if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all(): - return True - outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0] - for keyword in self.keywords: - if keyword in outputs: - return True - return False \ No newline at end of file diff --git a/q_align/model/__init__.py b/q_align/model/__init__.py deleted file mode 100644 index 6d6f0775a0abb2c3e220343a4feb05c70c2c7779..0000000000000000000000000000000000000000 --- a/q_align/model/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .modeling_mplug_owl2 import MPLUGOwl2LlamaForCausalLM -from .configuration_mplug_owl2 import MPLUGOwl2Config \ No newline at end of file diff --git a/q_align/model/__pycache__/__init__.cpython-310.pyc b/q_align/model/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 2385b4122537f406b59b779bbee7db97400c7970..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/__init__.cpython-311.pyc b/q_align/model/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index 2a0f4f90f4ca15acc6fce979cdde7c09a3854252..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/__init__.cpython-39.pyc b/q_align/model/__pycache__/__init__.cpython-39.pyc deleted file mode 100644 index 58122c87b9917b19fc6d37f5b4d9d6e56165fe5f..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/__init__.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/builder.cpython-310.pyc b/q_align/model/__pycache__/builder.cpython-310.pyc deleted file mode 100644 index 105a98b56eb0ec9844c7e91ebe97a3859c6da159..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/builder.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/builder.cpython-311.pyc b/q_align/model/__pycache__/builder.cpython-311.pyc deleted file mode 100644 index 433a8f78c22f1bb8cbed44a8212c7a135b6984cf..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/builder.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/builder.cpython-39.pyc b/q_align/model/__pycache__/builder.cpython-39.pyc deleted file mode 100644 index 29c5b7064f5ff98c67a0ce57a3a00f334451d0bb..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/builder.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-310.pyc b/q_align/model/__pycache__/configuration_mplug_owl2.cpython-310.pyc deleted file mode 100644 index 635940c1e254c29f31bf99267093652e79be3cde..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-311.pyc b/q_align/model/__pycache__/configuration_mplug_owl2.cpython-311.pyc deleted file mode 100644 index 25719ada8a0c968af25010fbd5e5210e41970fe1..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-39.pyc b/q_align/model/__pycache__/configuration_mplug_owl2.cpython-39.pyc deleted file mode 100644 index f5900c0e16a8406f291054065b730695ad319ed2..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/configuration_mplug_owl2.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-310.pyc b/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-310.pyc deleted file mode 100644 index 5696d2b89bfcbca12fb90f41d4659948835bc8e5..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-311.pyc b/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-311.pyc deleted file mode 100644 index 7f214501d903dd1fce9af34f44eb926aa7f9c151..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-39.pyc b/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-39.pyc deleted file mode 100644 index 7205da42d472fbe7c21978b1a00eb1c80d48c13e..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_attn_mask_utils.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_llama2.cpython-310.pyc b/q_align/model/__pycache__/modeling_llama2.cpython-310.pyc deleted file mode 100644 index cf3b452eb120657e9fdc922c2d9af36c4779a486..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_llama2.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_llama2.cpython-311.pyc b/q_align/model/__pycache__/modeling_llama2.cpython-311.pyc deleted file mode 100644 index 12c41d1db6becf19b2c92e71fcbcc644df70ff40..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_llama2.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_llama2.cpython-39.pyc b/q_align/model/__pycache__/modeling_llama2.cpython-39.pyc deleted file mode 100644 index cf4d5c16c742f3034faa01d7c025693d9145f074..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_llama2.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-310.pyc b/q_align/model/__pycache__/modeling_mplug_owl2.cpython-310.pyc deleted file mode 100644 index 57e4fcfc33a50f58b7c7f9728799eed476f64acc..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-311.pyc b/q_align/model/__pycache__/modeling_mplug_owl2.cpython-311.pyc deleted file mode 100644 index 3d8a41ee61a9e40ffc92f2390b655242ad5224ff..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-39.pyc b/q_align/model/__pycache__/modeling_mplug_owl2.cpython-39.pyc deleted file mode 100644 index c7f37ea2a8e9a32491babc6fa09766cd462475e4..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/modeling_mplug_owl2.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/visual_encoder.cpython-310.pyc b/q_align/model/__pycache__/visual_encoder.cpython-310.pyc deleted file mode 100644 index 5afa32d185606d4e67fa234c37fa7d3dd1a95ea9..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/visual_encoder.cpython-310.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/visual_encoder.cpython-311.pyc b/q_align/model/__pycache__/visual_encoder.cpython-311.pyc deleted file mode 100644 index dc26e07486aa49227b346f1940189272ff91b0d7..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/visual_encoder.cpython-311.pyc and /dev/null differ diff --git a/q_align/model/__pycache__/visual_encoder.cpython-39.pyc b/q_align/model/__pycache__/visual_encoder.cpython-39.pyc deleted file mode 100644 index 32fda8db614444b38bd7fb71951950478fd19487..0000000000000000000000000000000000000000 Binary files a/q_align/model/__pycache__/visual_encoder.cpython-39.pyc and /dev/null differ diff --git a/q_align/model/builder.py b/q_align/model/builder.py deleted file mode 100644 index 5da53f5ff3d39265636f154923173c49186e7fa4..0000000000000000000000000000000000000000 --- a/q_align/model/builder.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright 2023 Haotian Liu -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import os -import warnings -import shutil - -from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig -from transformers.models.clip.image_processing_clip import CLIPImageProcessor -import torch -from q_align.model import * -from icecream import ic -def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda"): - kwargs = {"device_map": device_map} - - if device != "cuda": - kwargs['device_map'] = {"": device} - - if load_8bit: - kwargs['load_in_8bit'] = True - elif load_4bit: - kwargs['load_in_4bit'] = True - kwargs['quantization_config'] = BitsAndBytesConfig( - load_in_4bit=True, - bnb_4bit_compute_dtype=torch.float16, - bnb_4bit_use_double_quant=True, - bnb_4bit_quant_type='nf4' - ) - else: - kwargs['torch_dtype'] = torch.float16 - if 'mplug_owl2' in model_name.lower(): - # Load LLaVA model - if 'lora' in model_name.lower() and model_base is None: - warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.') - if 'lora' in model_name.lower() and model_base is not None: - lora_cfg_pretrained = AutoConfig.from_pretrained(model_path) - tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) - print('Loading mPLUG-Owl2 from base model...') - model = MPLUGOwl2LlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs) - token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features - if model.lm_head.weight.shape[0] != token_num: - model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) - model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) - - print('Loading additional mPLUG-Owl2 weights...') - if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')): - non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu') - else: - # this is probably from HF Hub - from huggingface_hub import hf_hub_download - def load_from_hf(repo_id, filename, subfolder=None): - cache_file = hf_hub_download( - repo_id=repo_id, - filename=filename, - subfolder=subfolder) - return torch.load(cache_file, map_location='cpu') - non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin') - non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()} - if any(k.startswith('model.model.') for k in non_lora_trainables): - non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()} - model.load_state_dict(non_lora_trainables, strict=False) - - from peft import PeftModel - print('Loading LoRA weights...') - model = PeftModel.from_pretrained(model, model_path) - print('Merging LoRA weights...') - model = model.merge_and_unload() - print('Model is loaded...') - elif model_base is not None: - # this may be mm projector only - print('Loading mPLUG-Owl2 from base model...') - tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) - cfg_pretrained = AutoConfig.from_pretrained(model_path) - model = MPLUGOwl2LlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs) - else: - tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) - model = MPLUGOwl2LlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) - else: - # Load language model - if model_base is not None: - # PEFT model - from peft import PeftModel - tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) - model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, **kwargs) - print(f"Loading LoRA weights from {model_path}") - model = PeftModel.from_pretrained(model, model_path) - print(f"Merging weights") - model = model.merge_and_unload() - print('Convert to FP16...') - model.to(torch.float16) - else: - use_fast = False - tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) - model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) - - - vision_tower = model.get_model().vision_model - vision_tower.to(device=device, dtype=torch.float16) - image_processor = CLIPImageProcessor.from_pretrained(model_path) - - if hasattr(model.config, "max_sequence_length"): - context_len = model.config.max_sequence_length - else: - context_len = 2048 - - return tokenizer, model, image_processor, context_len \ No newline at end of file diff --git a/q_align/model/configuration_mplug_owl2.py b/q_align/model/configuration_mplug_owl2.py deleted file mode 100644 index e2e31a61cc919a694ef62929c705d91143be63d1..0000000000000000000000000000000000000000 --- a/q_align/model/configuration_mplug_owl2.py +++ /dev/null @@ -1,332 +0,0 @@ -# Copyright (c) Alibaba. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -import copy -import os -from typing import Union - -from transformers.configuration_utils import PretrainedConfig -from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES -from transformers.utils import logging -from transformers.models.auto import CONFIG_MAPPING - - -class LlamaConfig(PretrainedConfig): - r""" - This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA - model according to the specified arguments, defining the model architecture. Instantiating a configuration with the - defaults will yield a similar configuration to that of the LLaMA-7B. - - Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the - documentation from [`PretrainedConfig`] for more information. - - - Args: - vocab_size (`int`, *optional*, defaults to 32000): - Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the - `inputs_ids` passed when calling [`LlamaModel`] - hidden_size (`int`, *optional*, defaults to 4096): - Dimension of the hidden representations. - intermediate_size (`int`, *optional*, defaults to 11008): - Dimension of the MLP representations. - num_hidden_layers (`int`, *optional*, defaults to 32): - Number of hidden layers in the Transformer decoder. - num_attention_heads (`int`, *optional*, defaults to 32): - Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (`int`, *optional*): - This is the number of key_value heads that should be used to implement Grouped Query Attention. If - `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if - `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When - converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed - by meanpooling all the original heads within that group. For more details checkout [this - paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to - `num_attention_heads`. - hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): - The non-linear activation function (function or string) in the decoder. - max_position_embeddings (`int`, *optional*, defaults to 2048): - The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens, - Llama 2 up to 4096, CodeLlama up to 16384. - initializer_range (`float`, *optional*, defaults to 0.02): - The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (`float`, *optional*, defaults to 1e-06): - The epsilon used by the rms normalization layers. - use_cache (`bool`, *optional*, defaults to `True`): - Whether or not the model should return the last key/values attentions (not used by all models). Only - relevant if `config.is_decoder=True`. - pad_token_id (`int`, *optional*): - Padding token id. - bos_token_id (`int`, *optional*, defaults to 1): - Beginning of stream token id. - eos_token_id (`int`, *optional*, defaults to 2): - End of stream token id. - pretraining_tp (`int`, *optional*, defaults to 1): - Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this - document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is - necessary to ensure exact reproducibility of the pretraining results. Please refer to [this - issue](https://github.com/pytorch/pytorch/issues/76232). - tie_word_embeddings (`bool`, *optional*, defaults to `False`): - Whether to tie weight embeddings - rope_theta (`float`, *optional*, defaults to 10000.0): - The base period of the RoPE embeddings. - rope_scaling (`Dict`, *optional*): - Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling - strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is - `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update - `max_position_embeddings` to the expected new maximum. See the following thread for more information on how - these scaling strategies behave: - https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an - experimental feature, subject to breaking API changes in future versions. - attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): - Whether to use a bias in the query, key, value and output projection layers during self-attention. - - - ```python - >>> from transformers import LlamaModel, LlamaConfig - - >>> # Initializing a LLaMA llama-7b style configuration - >>> configuration = LlamaConfig() - - >>> # Initializing a model from the llama-7b style configuration - >>> model = LlamaModel(configuration) - - >>> # Accessing the model configuration - >>> configuration = model.config - ```""" - model_type = "llama" - keys_to_ignore_at_inference = ["past_key_values"] - - def __init__( - self, - vocab_size=32000, - hidden_size=4096, - intermediate_size=11008, - num_hidden_layers=32, - num_attention_heads=32, - num_key_value_heads=None, - hidden_act="silu", - max_position_embeddings=2048, - initializer_range=0.02, - rms_norm_eps=1e-6, - use_cache=True, - pad_token_id=None, - bos_token_id=1, - eos_token_id=2, - pretraining_tp=1, - tie_word_embeddings=False, - rope_theta=10000.0, - rope_scaling=None, - attention_bias=False, - **kwargs, - ): - self.vocab_size = vocab_size - self.max_position_embeddings = max_position_embeddings - self.hidden_size = hidden_size - self.intermediate_size = intermediate_size - self.num_hidden_layers = num_hidden_layers - self.num_attention_heads = num_attention_heads - - # for backward compatibility - if num_key_value_heads is None: - num_key_value_heads = num_attention_heads - - self.num_key_value_heads = num_key_value_heads - self.hidden_act = hidden_act - self.initializer_range = initializer_range - self.rms_norm_eps = rms_norm_eps - self.pretraining_tp = pretraining_tp - self.use_cache = use_cache - self.rope_theta = rope_theta - self.rope_scaling = rope_scaling - self._rope_scaling_validation() - self.attention_bias = attention_bias - - super().__init__( - pad_token_id=pad_token_id, - bos_token_id=bos_token_id, - eos_token_id=eos_token_id, - tie_word_embeddings=tie_word_embeddings, - **kwargs, - ) - - def _rope_scaling_validation(self): - """ - Validate the `rope_scaling` configuration. - """ - if self.rope_scaling is None: - return - - if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2: - raise ValueError( - "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, " - f"got {self.rope_scaling}" - ) - rope_scaling_type = self.rope_scaling.get("type", None) - rope_scaling_factor = self.rope_scaling.get("factor", None) - if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: - raise ValueError( - f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" - ) - if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0: - raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}") - - -class MplugOwlVisionConfig(PretrainedConfig): - r""" - This is the configuration class to store the configuration of a [`MplugOwlVisionModel`]. It is used to instantiate - a - mPLUG-Owl vision encoder according to the specified arguments, defining the model architecture. Instantiating a - configuration defaults will yield a similar configuration to that of the mPLUG-Owl - [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b) architecture. - - Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the - documentation from [`PretrainedConfig`] for more information. - - Args: - hidden_size (`int`, *optional*, defaults to 768): - Dimensionality of the encoder layers and the pooler layer. - intermediate_size (`int`, *optional*, defaults to 3072): - Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. - num_hidden_layers (`int`, *optional*, defaults to 12): - Number of hidden layers in the Transformer encoder. - num_attention_heads (`int`, *optional*, defaults to 12): - Number of attention heads for each attention layer in the Transformer encoder. - image_size (`int`, *optional*, defaults to 224): - The size (resolution) of each image. - patch_size (`int`, *optional*, defaults to 32): - The size (resolution) of each patch. - hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`): - The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, - `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported. - layer_norm_eps (`float`, *optional*, defaults to 1e-5): - The epsilon used by the layer normalization layers. - attention_dropout (`float`, *optional*, defaults to 0.0): - The dropout ratio for the attention probabilities. - initializer_range (`float`, *optional*, defaults to 0.02): - The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - initializer_factor (`float`, *optional*, defaults to 1): - A factor for initializing all weight matrices (should be kept to 1, used internally for initialization - testing). - - - ```""" - - model_type = "mplug_owl_vision_model" - - def __init__( - self, - hidden_size=1024, - intermediate_size=4096, - projection_dim=768, - num_hidden_layers=24, - num_attention_heads=16, - num_channels=3, - image_size=448, - patch_size=14, - hidden_act="quick_gelu", - layer_norm_eps=1e-6, - attention_dropout=0.0, - initializer_range=0.02, - initializer_factor=1.0, - use_flash_attn=False, - **kwargs, - ): - super().__init__(**kwargs) - self.hidden_size = hidden_size - self.intermediate_size = intermediate_size - self.projection_dim = projection_dim - self.num_hidden_layers = num_hidden_layers - self.num_attention_heads = num_attention_heads - self.num_channels = num_channels - self.patch_size = patch_size - self.image_size = image_size - self.initializer_range = initializer_range - self.initializer_factor = initializer_factor - self.attention_dropout = attention_dropout - self.layer_norm_eps = layer_norm_eps - self.hidden_act = hidden_act - self.use_flash_attn = use_flash_attn - - @classmethod - def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": - config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs) - - # get the vision config dict if we are loading from MplugOwlConfig - if config_dict.get("model_type") == "mplug-owl": - config_dict = config_dict["vision_config"] - - if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: - logger.warning( - f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " - f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." - ) - - return cls.from_dict(config_dict, **kwargs) - - -class MplugOwlVisualAbstractorConfig(PretrainedConfig): - model_type = "mplug_owl_visual_abstract" - - def __init__( - self, - num_learnable_queries=64, - hidden_size=1024, - num_hidden_layers=6, - num_attention_heads=16, - intermediate_size=2816, - attention_probs_dropout_prob=0., - initializer_range=0.02, - layer_norm_eps=1e-6, - encoder_hidden_size=1024, - grid_size=None, - **kwargs, - ): - super().__init__(**kwargs) - self.hidden_size = hidden_size - self.num_learnable_queries = num_learnable_queries - self.num_hidden_layers = num_hidden_layers - self.num_attention_heads = num_attention_heads - self.intermediate_size = intermediate_size - self.attention_probs_dropout_prob = attention_probs_dropout_prob - self.initializer_range = initializer_range - self.layer_norm_eps = layer_norm_eps - self.encoder_hidden_size = encoder_hidden_size - self.grid_size = grid_size if grid_size else 32 - - @classmethod - def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": - config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs) - - # get the visual_abstractor config dict if we are loading from MplugOwlConfig - if config_dict.get("model_type") == "mplug-owl": - config_dict = config_dict["abstractor_config"] - - if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: - logger.warning( - f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " - f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." - ) - - return cls.from_dict(config_dict, **kwargs) - - - -DEFAULT_VISUAL_CONFIG = { - "visual_model": MplugOwlVisionConfig().to_dict(), - "visual_abstractor": MplugOwlVisualAbstractorConfig().to_dict() -} - -class MPLUGOwl2Config(LlamaConfig): - model_type = "mplug_owl2" - def __init__(self, visual_config=None, **kwargs): - if visual_config is None: - self.visual_config = DEFAULT_VISUAL_CONFIG - else: - self.visual_config = visual_config - - super().__init__( - **kwargs, - ) - -if __name__ == "__main__": - print(MplugOwlVisionConfig().to_dict()) \ No newline at end of file diff --git a/q_align/model/convert_mplug_owl2_weight_to_hf.py b/q_align/model/convert_mplug_owl2_weight_to_hf.py deleted file mode 100644 index 8288a9a6a9b5d7a1a4ec58af6a53b14d4b266580..0000000000000000000000000000000000000000 --- a/q_align/model/convert_mplug_owl2_weight_to_hf.py +++ /dev/null @@ -1,395 +0,0 @@ -# Copyright 2023 DAMO Academy and The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import argparse -import gc -import json -import math -import os -import shutil -import warnings - -import torch - -from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer -from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig -from .modeling_mplug_owl2 import MPLUGOwl2LlamaForCausalLM - -try: - from transformers import LlamaTokenizerFast -except ImportError as e: - warnings.warn(e) - warnings.warn( - "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion" - ) - LlamaTokenizerFast = None - -""" -Sample usage: - -``` -python3 /pure-mlo-scratch/sfan/model-parallel-trainer/llama2megatron/convert_llama2hf.py \ - --input_dir /pure-mlo-scratch/llama/ --model_size 7 --output_dir /pure-mlo-scratch/llama/converted_HF_7B -``` - -Thereafter, models can be loaded via: - -```py -from transformers import LlamaForCausalLM, LlamaTokenizer - -model = LlamaForCausalLM.from_pretrained("/output/path") -tokenizer = LlamaTokenizer.from_pretrained("/output/path") -``` - -Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions -come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). -""" - -llama_s2layer = {7: 32, 13: 40, 30: 60, 65: 80, 70: 80} -llama_s2heads = {7: 32, 13: 40, 30: 52, 65: 64, 70: 64} -llama_s2dense = {7: 11008, 13: 13824, 30: 17920, 65: 22016, - 70: 28672} # should be (2/3)*4*d, but it isn't exaclty that -llama_s2hidden = {7: 4096, 13: 5120, 32: 6656, 65: 8192, 70: 8192} - - -def compute_intermediate_size(n): - return int(math.ceil(n * 8 / 3) + 255) // 256 * 256 - - -def read_json(path): - with open(path, "r") as f: - return json.load(f) - - -def write_json(text, path): - with open(path, "w") as f: - json.dump(text, f) - - -def write_model(model_path, - input_base_path, - model_size, - num_input_shards=1, - num_output_shards=2, - skip_permute=True, - norm_eps=1e-05): - # if os.path.exists(model_path): - # shutil.rmtree(model_path) - os.makedirs(model_path, exist_ok=True) - # tmp_model_path = os.path.join(model_path, "tmp") - tmp_model_path = model_path - os.makedirs(tmp_model_path, exist_ok=True) - - num_shards = num_input_shards - n_layers = llama_s2layer[model_size] - n_heads = llama_s2heads[model_size] - n_heads_per_shard = n_heads // num_shards - n_dense = llama_s2dense[model_size] - n_hidden = llama_s2hidden[model_size] - hidden_per_head = n_hidden // n_heads - base = 10000.0 - inv_freq = 1.0 / (base ** (torch.arange(0, hidden_per_head, 2).float() / hidden_per_head)) - - # permute for sliced rotary - def permute(w, skip_permute=skip_permute): - if skip_permute: - return w - return w.view(n_heads, n_hidden // n_heads // 2, 2, n_hidden).transpose(1, 2).reshape(n_hidden, n_hidden) - - print(f"Fetching all parameters from the checkpoint at {input_base_path}.") - # Load weights - if num_shards==1: - # Not sharded - # (The sharded implementation would also work, but this is simpler.) - # /pure-mlo-scratch/alhernan/megatron-data/checkpoints/llama2-7b-tp4-pp1-optim/release/mp_rank_00/model_optim_rng.pt - if os.path.exists(os.path.join(input_base_path, 'release')): - filename = os.path.join(input_base_path, 'release', 'mp_rank_00', 'model_optim_rng.pt') - elif input_base_path.split('/')[-1].startswith('iter_'): - iteration = eval(input_base_path.split('/')[-1].replace('iter_', '').lstrip('0')) - load_dir = '/'.join(input_base_path.split('/')[:-1]) - filename = os.path.join(input_base_path, 'mp_rank_00', 'model_optim_rng.pt') - if not os.path.exists(filename): - filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') - else: - tracker_filename = os.path.join(input_base_path, 'latest_checkpointed_iteration.txt') - with open(tracker_filename, 'r') as f: - metastring = f.read().strip() - iteration = 'iter_{:07d}'.format(int(metastring)) - filename = os.path.join(input_base_path, iteration, 'mp_rank_00', 'model_optim_rng.pt') - if not os.path.exists(filename): - filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') - original_filename = filename - loaded = torch.load(filename, map_location="cpu")['model']['language_model'] - - else: - # Sharded - filenames = [] - for i in range(num_shards): - if os.path.exists(os.path.join(input_base_path, 'release')): - filename = os.path.join(input_base_path, 'release', f'mp_rank_{i:02d}', 'model_optim_rng.pt') - else: - tracker_filename = os.path.join(input_base_path, 'latest_checkpointed_iteration.txt') - with open(tracker_filename, 'r') as f: - metastring = f.read().strip() - iteration = 'iter_{:07d}'.format(int(metastring)) - filename = os.path.join(input_base_path, iteration, f'mp_rank_{i:02d}', 'model_optim_rng.pt') - if not os.path.exists(filename): - filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') - filenames.append(filename) - loaded = [ - torch.load(filenames[i], map_location="cpu")['model']['language_model'] - for i in range(num_shards) - ] - - print('Llama-Megatron Loaded!') - param_count = 0 - index_dict = {"weight_map": {}} - - print(f'Weighted Converting for {n_layers} layers...') - for layer_i in range(n_layers): - print(layer_i) - filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" - if num_shards == 1: - # Unsharded - state_dict = { - f"model.layers.{layer_i}.self_attn.q_proj.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.q_proj.weight"], - f"model.layers.{layer_i}.self_attn.k_proj.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.0.weight"], - f"model.layers.{layer_i}.self_attn.v_proj.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.0.weight"], - f"model.layers.{layer_i}.self_attn.k_proj.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.1.weight"], - f"model.layers.{layer_i}.self_attn.v_proj.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.1.weight"], - f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.o_proj.weight"], - f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.gate_proj.weight"], - f"model.layers.{layer_i}.mlp.down_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.down_proj.weight"], - f"model.layers.{layer_i}.mlp.up_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.up_proj.weight"], - f"model.layers.{layer_i}.input_layernorm.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.input_layernorm.multiway.0.weight"], - f"model.layers.{layer_i}.post_attention_layernorm.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.post_attention_layernorm.multiway.0.weight"], - f"model.layers.{layer_i}.input_layernorm.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.input_layernorm.multiway.1.weight"], - f"model.layers.{layer_i}.post_attention_layernorm.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.post_attention_layernorm.multiway.1.weight"], - } - else: - raise NotImplemented -# else: -# # Sharded -# # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share -# # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is -# # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. - -# state_dict = { -# f"model.layers.{layer_i}.input_layernorm.weight": loaded[0]['encoder'][ -# f"layers.{layer_i}.input_layernorm.multiway.0.weight" -# ].clone(), -# f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0]['encoder'][ -# f"layers.{layer_i}.post_attention_layernorm.multiway.0.weight" -# ].clone(), -# } - -# wqs, wks, wvs, ffn_w1s, ffn_w3s = [], [], [], [], [] -# for shard_idx in range(num_shards): -# wqs.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.q_proj.weight"]) -# wks.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.0.weight"]) -# wvs.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.0.weight"]) - -# state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute( -# torch.cat( -# [ -# wq.view(n_heads_per_shard, hidden_per_head, n_hidden) -# for wq in range(wqs) -# ], -# dim=0, -# ).reshape(n_hidden, n_hidden) -# ) -# state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute( -# torch.cat( -# [ -# wk.view(n_heads_per_shard, hidden_per_head, n_hidden) -# for wk in range(wks) -# ], -# dim=0, -# ).reshape(n_hidden, n_hidden) -# ) -# state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat( -# [ -# wv.view(n_heads_per_shard, hidden_per_head, n_hidden) -# for wv in range(wvs) -# ], -# dim=0, -# ).reshape(n_hidden, n_hidden) - -# state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat( -# [loaded[i]['encoder'][f"layers.{layer_i}.self_attention.o_proj.weight"] for i in range(num_shards)], dim=1 -# ) -# state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat( -# [loaded[i]['encoder'][f"layers.{layer_i}.mlp.gate_proj.weight"] for i in range(num_shards)], dim=0 -# ) -# state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat( -# [loaded[i]['encoder'][f"layers.{layer_i}.mlp.down_proj.weight"] for i in range(num_shards)], dim=1 -# ) -# state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat( -# [loaded[i]['encoder'][f"layers.{layer_i}.mlp.up_proj.weight"] for i in range(num_shards)], dim=0 -# ) - - state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq - for k, v in state_dict.items(): - index_dict["weight_map"][k] = filename - param_count += v.numel() - torch.save(state_dict, os.path.join(tmp_model_path, filename)) - print(f'Sharded file saved to {filename}') - - filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" - if num_shards==1: - # Unsharded - state_dict = { - "model.embed_tokens.weight": loaded['embedding']['word_embeddings']['weight'], - "model.norm.weight": loaded['encoder']['norm.weight'], - "lm_head.weight": loaded['encoder']['lm_head.weight'], - } - else: - state_dict = { - "model.embed_tokens.weight": loaded[0]['embedding']['word_embeddings']['weight'], - "model.norm.weight": loaded[0]['encoder']['norm.weight'], - "lm_head.weight": loaded[0]['encoder']['lm_head.weight'], - } - - - loaded_all = torch.load(original_filename, map_location="cpu")['model'] - # Vision Part - state_dict.update({ - "model.vision_model.embeddings.cls_token": loaded_all['vision_model']['cls_token'], - "model.vision_model.embeddings.patch_embed.weight": loaded_all['vision_model']['patch_embed']['weight'], - "model.vision_model.embeddings.position_embedding": loaded_all['vision_model']['position_embeddings'], - "model.vision_model.embeddings.pre_layernorm.bias": loaded_all['vision_model']['pre_layernorm']['bias'], - "model.vision_model.embeddings.pre_layernorm.weight": loaded_all['vision_model']['pre_layernorm']['weight'], - "model.vision_model.post_layernorm.bias": loaded_all['vision_model']['transformer']['final_layernorm.bias'], - "model.vision_model.post_layernorm.weight": loaded_all['vision_model']['transformer']['final_layernorm.weight'], - }) - for v_layer_idx in range(24): - state_dict.update({ - f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.weight'], - f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.weight'], - f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.weight'], - f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.weight'], - f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.weight'], - f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.bias'], - f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.weight'], - }) - - # Abstractor Part - state_dict.update({ - "model.visual_abstractor.query_embeds": loaded_all['vision_abstractor']['learnable_queries'], - "model.visual_abstractor.visual_fc.bias": loaded_all['vision_abstractor']['visual_fc']['bias'], - "model.visual_abstractor.visual_fc.weight": loaded_all['vision_abstractor']['visual_fc']['weight'], - "model.visual_abstractor.vit_eos": loaded_all['vision_abstractor']['vit_eos'], - }) - for v_layer_idx in range(6): - state_dict.update({ - # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.k_pos_embed": - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.weight"], - # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.q_pos_embed": "pytorch_model-00004-of-00004.bin", - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.weight"], - - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.weight"], - - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.weight"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.bias"], - f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.weight"], - }) - - for k, v in state_dict.items(): - index_dict["weight_map"][k] = filename - param_count += v.numel() - torch.save(state_dict, os.path.join(tmp_model_path, filename)) - - # Write configs - index_dict["metadata"] = {"total_size": param_count * 2} - write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json")) - - config = MPLUGOwl2Config() - config.save_pretrained(tmp_model_path) - - # Make space so we can load the model properly now. - del state_dict - del loaded - del loaded_all - gc.collect() - -def write_tokenizer(tokenizer_path, input_tokenizer_path): - # Initialize the tokenizer based on the `spm` model - tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast - print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.") - tokenizer = tokenizer_class(input_tokenizer_path) - tokenizer.save_pretrained(tokenizer_path) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument( - "--input_dir", - help="Location of LLaMA_Megatron weights", - ) - parser.add_argument( - "--model_size", - type=int, - default=7, - choices=[7, 13, 30, 65, 70], - ) - parser.add_argument( - "--num_input_shards", - type=int, - default=1, - ) - parser.add_argument( - "--num_output_shards", - type=int, - default=1, - ) - parser.add_argument('--skip_permute', action='store_true') - - parser.add_argument( - "--output_dir", - help="Location to write HF model and tokenizer", - ) - - args = parser.parse_args() - write_model( - model_path=args.output_dir, - input_base_path=args.input_dir, - model_size=args.model_size, - num_input_shards=args.num_input_shards, - num_output_shards=args.num_output_shards, - skip_permute=args.skip_permute - ) - - -if __name__ == "__main__": - main() diff --git a/q_align/model/modeling_attn_mask_utils.py b/q_align/model/modeling_attn_mask_utils.py deleted file mode 100644 index c2583a2dd5a09b1119c849ca00f954198d078799..0000000000000000000000000000000000000000 --- a/q_align/model/modeling_attn_mask_utils.py +++ /dev/null @@ -1,247 +0,0 @@ -# Copyright 2023 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import List, Optional, Tuple, Union - -import torch - - -class AttentionMaskConverter: - """ - A utility attention mask class that allows one to: - - Create a causal 4d mask - - Create a causal 4d mask with slided window - - Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length, - key_value_length) that can be multiplied with attention scores - - Parameters: - is_causal (`bool`): - Whether the attention mask should be a uni-directional (causal) or bi-directional mask. - - sliding_window (`int`, *optional*): - Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer. - """ - - def __init__(self, is_causal: bool, sliding_window: Optional[int] = None): - self.is_causal = is_causal - self.sliding_window = sliding_window - - if self.sliding_window is not None and self.sliding_window <= 0: - raise ValueError( - f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`" - ) - - def to_causal_4d( - self, - batch_size: int, - query_length: int, - key_value_length: int, - dtype: torch.dtype = torch.float32, - device: Union[torch.device, "str"] = "cpu", - ) -> torch.Tensor: - """ - Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative - bias to upper right hand triangular matrix (causal mask). - """ - if not self.is_causal: - raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.") - - # If shape is not cached, create a new causal mask and cache it - input_shape = (batch_size, query_length) - past_key_values_length = key_value_length - query_length - - # create causal mask - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - causal_4d_mask = None - if input_shape[-1] > 1 or self.sliding_window is not None: - causal_4d_mask = self._make_causal_mask( - input_shape, - dtype, - device=device, - past_key_values_length=past_key_values_length, - sliding_window=self.sliding_window, - ) - - return causal_4d_mask - - def to_4d( - self, - attention_mask_2d: torch.Tensor, - query_length: int, - key_value_length: Optional[int] = None, - dtype: torch.dtype = torch.float32, - ) -> torch.Tensor: - """ - Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length, - key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is - causal, a causal mask will be added. - """ - input_shape = (attention_mask_2d.shape[0], query_length) - - # create causal mask - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - causal_4d_mask = None - if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal: - if key_value_length is None: - raise ValueError( - "This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask." - ) - - past_key_values_length = key_value_length - query_length - causal_4d_mask = self._make_causal_mask( - input_shape, - dtype, - device=attention_mask_2d.device, - past_key_values_length=past_key_values_length, - sliding_window=self.sliding_window, - ) - elif self.sliding_window is not None: - raise NotImplementedError("Sliding window is currently only implemented for causal masking") - - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to( - attention_mask_2d.device - ) - expanded_4d_mask = expanded_attn_mask if causal_4d_mask is None else expanded_attn_mask + causal_4d_mask - - return expanded_4d_mask - - @staticmethod - def _make_causal_mask( - input_ids_shape: torch.Size, - dtype: torch.dtype, - device: torch.device, - past_key_values_length: int = 0, - sliding_window: Optional[int] = None, - ): - """ - Make causal mask used for bi-directional self-attention. - """ - bsz, tgt_len = input_ids_shape - mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) - mask_cond = torch.arange(mask.size(-1), device=device) - mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) - - mask = mask.to(dtype) - - if past_key_values_length > 0: - mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) - - # add lower triangular sliding window mask if necessary - if sliding_window is not None: - diagonal = past_key_values_length - sliding_window + 1 - - context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal) - mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min) - - return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) - - @staticmethod - def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): - """ - Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. - """ - bsz, src_len = mask.size() - tgt_len = tgt_len if tgt_len is not None else src_len - - expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) - - inverted_mask = 1.0 - expanded_mask - - return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) - - -def _prepare_4d_causal_attention_mask( - attention_mask: Optional[torch.Tensor], - input_shape: Union[torch.Size, Tuple, List], - inputs_embeds: torch.Tensor, - past_key_values_length: int, - sliding_window: Optional[int] = None, -): - """ - Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape - `(batch_size, key_value_length)` - - Args: - attention_mask (`torch.Tensor` or `None`): - A 2D attention mask of shape `(batch_size, key_value_length)` - input_shape (`tuple(int)` or `list(int)` or `torch.Size`): - The input shape should be a tuple that defines `(batch_size, query_length)`. - inputs_embeds (`torch.Tensor`): - The embedded inputs as a torch Tensor. - past_key_values_length (`int`): - The length of the key value cache. - sliding_window (`int`, *optional*): - If the model uses windowed attention, a sliding window should be passed. - """ - attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window) - - key_value_length = input_shape[-1] + past_key_values_length - - # 4d mask is passed through the layers - if attention_mask is not None: - attention_mask = attn_mask_converter.to_4d( - attention_mask, input_shape[-1], key_value_length, dtype=inputs_embeds.dtype - ) - else: - attention_mask = attn_mask_converter.to_causal_4d( - input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device - ) - - return attention_mask - - -def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): - """ - Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape - `(batch_size, key_value_length)` - - Args: - mask (`torch.Tensor` or `None`): - A 2D attention mask of shape `(batch_size, key_value_length)` - dtype (`torch.dtype`): - The torch dtype the created mask shall have. - tgt_len (`int`): - The target length or query length the created mask shall have. - """ - return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len) - - -def _create_4d_causal_attention_mask( - input_shape: Union[torch.Size, Tuple, List], - dtype: torch.dtype, - device: torch.device, - past_key_values_length: int = 0, - sliding_window: Optional[int] = None, -): - """ - Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` - - Args: - input_shape (`tuple(int)` or `list(int)` or `torch.Size`): - The input shape should be a tuple that defines `(batch_size, query_length)`. - dtype (`torch.dtype`): - The torch dtype the created mask shall have. - device (`int`): - The torch device the created mask shall have. - sliding_window (`int`, *optional*): - If the model uses windowed attention, a sliding window should be passed. - """ - attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window) - - key_value_length = past_key_values_length + input_shape[-1] - attention_mask = attn_mask_converter.to_causal_4d( - input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device - ) - - return attention_mask \ No newline at end of file diff --git a/q_align/model/modeling_llama2.py b/q_align/model/modeling_llama2.py deleted file mode 100644 index 2dbc5738e4b456bfee4035c3cc1bba7576118e91..0000000000000000000000000000000000000000 --- a/q_align/model/modeling_llama2.py +++ /dev/null @@ -1,486 +0,0 @@ -import math -import warnings -from functools import partial -from typing import List, Optional, Tuple, Union - -import torch -import torch.nn.functional as F -import torch.utils.checkpoint -from torch import nn - -import transformers -from transformers.models.llama.modeling_llama import * -from transformers.configuration_utils import PretrainedConfig -from transformers.utils import logging - -from .modeling_attn_mask_utils import _prepare_4d_causal_attention_mask -from .configuration_mplug_owl2 import LlamaConfig - -class MultiwayNetwork(nn.Module): - - def __init__(self, module_provider, num_multiway=2): - super(MultiwayNetwork, self).__init__() - - self.multiway = torch.nn.ModuleList([module_provider() for _ in range(num_multiway)]) - - def forward(self, hidden_states, multiway_indices): - - if len(self.multiway) == 1: - return self.multiway[0](hidden_states) - - output_hidden_states = torch.empty_like(hidden_states) - - for idx, subway in enumerate(self.multiway): - local_indices = multiway_indices.eq(idx).nonzero(as_tuple=True) - hidden = hidden_states[local_indices].unsqueeze(1).contiguous() - if hidden.numel(): - output = subway(hidden) - if isinstance(output, tuple): - output = output[0] - output = output.squeeze(1) - output_hidden_states[local_indices] = output - - return output_hidden_states.contiguous() - - -class LlamaAttention(nn.Module): - """Multi-headed attention from 'Attention Is All You Need' paper""" - - def __init__(self, config: LlamaConfig): - super().__init__() - self.config = config - self.hidden_size = config.hidden_size - self.num_heads = config.num_attention_heads - self.head_dim = self.hidden_size // self.num_heads - self.num_key_value_heads = config.num_key_value_heads - self.num_key_value_groups = self.num_heads // self.num_key_value_heads - self.max_position_embeddings = config.max_position_embeddings - self.rope_theta = config.rope_theta - - if (self.head_dim * self.num_heads) != self.hidden_size: - raise ValueError( - f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" - f" and `num_heads`: {self.num_heads})." - ) - self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) - self.k_proj = MultiwayNetwork(module_provider=partial( - nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias) - ) - self.v_proj = MultiwayNetwork(module_provider=partial( - nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias) - ) - self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) - self._init_rope() - - def _init_rope(self): - if self.config.rope_scaling is None: - self.rotary_emb = LlamaRotaryEmbedding( - self.head_dim, - max_position_embeddings=self.max_position_embeddings, - base=self.rope_theta, - ) - else: - scaling_type = self.config.rope_scaling["type"] - scaling_factor = self.config.rope_scaling["factor"] - if scaling_type == "linear": - self.rotary_emb = LlamaLinearScalingRotaryEmbedding( - self.head_dim, - max_position_embeddings=self.max_position_embeddings, - scaling_factor=scaling_factor, - base=self.rope_theta, - ) - elif scaling_type == "dynamic": - self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( - self.head_dim, - max_position_embeddings=self.max_position_embeddings, - scaling_factor=scaling_factor, - base=self.rope_theta, - ) - else: - raise ValueError(f"Unknown RoPE scaling type {scaling_type}") - - def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): - return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() - - def forward( - self, - hidden_states: torch.Tensor, - modality_indicators: torch.Tensor, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: bool = False, - use_cache: bool = False, - padding_mask: Optional[torch.LongTensor] = None, - ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - bsz, q_len, _ = hidden_states.size() - - query_states = self.q_proj(hidden_states, ) - key_states = self.k_proj(hidden_states, modality_indicators) - value_states = self.v_proj(hidden_states, modality_indicators) - - query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - kv_seq_len += past_key_value[0].shape[-2] - cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) - - if past_key_value is not None: - # reuse k, v, self_attention - key_states = torch.cat([past_key_value[0], key_states], dim=2) - value_states = torch.cat([past_key_value[1], value_states], dim=2) - - past_key_value = (key_states, value_states) if use_cache else None - - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) - - attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) - - if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): - raise ValueError( - f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" - f" {attn_weights.size()}" - ) - - if attention_mask is not None: - if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): - raise ValueError( - f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" - ) - attn_weights = attn_weights + attention_mask - - # upcast attention to fp32 - attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) - attn_output = torch.matmul(attn_weights, value_states) - - if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): - raise ValueError( - f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" - f" {attn_output.size()}" - ) - - attn_output = attn_output.transpose(1, 2).contiguous() - - attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) - - attn_output = self.o_proj(attn_output) - - if not output_attentions: - attn_weights = None - - return attn_output, attn_weights, past_key_value - - - -class LlamaDecoderLayer(nn.Module): - def __init__(self, config: LlamaConfig): - super().__init__() - self.hidden_size = config.hidden_size - self.self_attn = LlamaAttention(config=config) - self.mlp = LlamaMLP(config) - self.input_layernorm = MultiwayNetwork(module_provider=partial( - LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps - )) - self.post_attention_layernorm = MultiwayNetwork(module_provider=partial( - LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps - )) - - def forward( - self, - hidden_states: torch.Tensor, - modality_indicators: torch.Tensor = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: Optional[bool] = False, - use_cache: Optional[bool] = False, - ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: - """ - Args: - hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` - attention_mask (`torch.FloatTensor`, *optional*): attention mask of size - `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - use_cache (`bool`, *optional*): - If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding - (see `past_key_values`). - past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states - """ - - residual = hidden_states - - hidden_states = self.input_layernorm(hidden_states, modality_indicators) - - # Self Attention - hidden_states, self_attn_weights, present_key_value = self.self_attn( - hidden_states=hidden_states, - modality_indicators=modality_indicators, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_value=past_key_value, - output_attentions=output_attentions, - use_cache=use_cache, - ) - hidden_states = residual + hidden_states - - # Fully Connected - residual = hidden_states - hidden_states = self.post_attention_layernorm(hidden_states, modality_indicators) - hidden_states = self.mlp(hidden_states) - hidden_states = residual + hidden_states - - outputs = (hidden_states,) - - if output_attentions: - outputs += (self_attn_weights,) - - if use_cache: - outputs += (present_key_value,) - - return outputs - - -def model_forward( - self, - input_ids: torch.LongTensor = None, - modality_indicators: torch.Tensor = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, -) -> Union[Tuple, BaseModelOutputWithPast]: - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - use_cache = use_cache if use_cache is not None else self.config.use_cache - - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - # retrieve input_ids and inputs_embeds - if input_ids is not None and inputs_embeds is not None: - raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") - elif input_ids is not None: - batch_size, seq_length = input_ids.shape - elif inputs_embeds is not None: - batch_size, seq_length, _ = inputs_embeds.shape - else: - raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") - - seq_length_with_past = seq_length - past_key_values_length = 0 - - if past_key_values is not None: - past_key_values_length = past_key_values[0][0].shape[2] - seq_length_with_past = seq_length_with_past + past_key_values_length - - if position_ids is None: - device = input_ids.device if input_ids is not None else inputs_embeds.device - position_ids = torch.arange( - past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device - ) - position_ids = position_ids.unsqueeze(0).view(-1, seq_length) - else: - position_ids = position_ids.view(-1, seq_length).long() - - if inputs_embeds is None: - inputs_embeds = self.embed_tokens(input_ids) - # embed positions - if attention_mask is None: - attention_mask = torch.ones( - (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device - ) - attention_mask = self._prepare_decoder_attention_mask( - attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length - ) - - hidden_states = inputs_embeds - - if self.gradient_checkpointing and self.training: - if use_cache: - logger.warning_once( - "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." - ) - use_cache = False - - # decoder layers - all_hidden_states = () if output_hidden_states else None - all_self_attns = () if output_attentions else None - next_decoder_cache = () if use_cache else None - - for idx, decoder_layer in enumerate(self.layers): - if output_hidden_states: - all_hidden_states += (hidden_states,) - - past_key_value = past_key_values[idx] if past_key_values is not None else None - - if self.gradient_checkpointing and self.training: - - def create_custom_forward(module): - def custom_forward(*inputs): - # None for past_key_value - return module(*inputs, past_key_value, output_attentions) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(decoder_layer), - hidden_states, - modality_indicators, - attention_mask, - position_ids, - ) - else: - layer_outputs = decoder_layer( - hidden_states, - modality_indicators=modality_indicators, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_value=past_key_value, - output_attentions=output_attentions, - use_cache=use_cache, - ) - - hidden_states = layer_outputs[0] - - if use_cache: - next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) - - if output_attentions: - all_self_attns += (layer_outputs[1],) - - hidden_states = self.norm(hidden_states) - - # add hidden states from the last decoder layer - if output_hidden_states: - all_hidden_states += (hidden_states,) - - next_cache = next_decoder_cache if use_cache else None - if not return_dict: - return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) - return BaseModelOutputWithPast( - last_hidden_state=hidden_states, - past_key_values=next_cache, - hidden_states=all_hidden_states, - attentions=all_self_attns, - ) - - -def causal_model_forward( - self, - input_ids: torch.LongTensor = None, - modality_indicators: torch.Tensor = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, -) -> Union[Tuple, CausalLMOutputWithPast]: - r""" - Args: - labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): - Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., - config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored - (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. - - Returns: - - Example: - - ```python - >>> from transformers import AutoTokenizer, LlamaForCausalLM - - >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) - >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) - - >>> prompt = "Hey, are you conscious? Can you talk to me?" - >>> inputs = tokenizer(prompt, return_tensors="pt") - - >>> # Generate - >>> generate_ids = model.generate(inputs.input_ids, max_length=30) - >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] - "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." - ```""" - - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) - outputs = self.model( - input_ids=input_ids, - modality_indicators=modality_indicators, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_values=past_key_values, - inputs_embeds=inputs_embeds, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - hidden_states = outputs[0] - if self.config.pretraining_tp > 1: - lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) - logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] - logits = torch.cat(logits, dim=-1) - else: - logits = self.lm_head(hidden_states) - logits = logits.float() - - loss = None - if labels is not None: - # Shift so that tokens < n predict n - shift_logits = logits[..., :-1, :].contiguous() - shift_labels = labels[..., 1:].contiguous() - # Flatten the tokens - loss_fct = CrossEntropyLoss() - shift_logits = shift_logits.view(-1, self.config.vocab_size) - shift_labels = shift_labels.view(-1) - # Enable model parallelism - shift_labels = shift_labels.to(shift_logits.device) - loss = loss_fct(shift_logits, shift_labels) - - if not return_dict: - output = (logits,) + outputs[1:] - return (loss,) + output if loss is not None else output - - return CausalLMOutputWithPast( - loss=loss, - logits=logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - -def replace_llama_modality_adaptive(): - transformers.models.llama.configuration_llama.LlamaConfig = LlamaConfig - transformers.models.llama.modeling_llama.LlamaAttention = LlamaAttention - transformers.models.llama.modeling_llama.LlamaDecoderLayer = LlamaDecoderLayer - transformers.models.llama.modeling_llama.LlamaModel.forward = model_forward - transformers.models.llama.modeling_llama.LlamaForCausalLM.forward = causal_model_forward - - -if __name__ == "__main__": - replace_llama_modality_adaptive() - config = transformers.LlamaConfig.from_pretrained('/cpfs01/shared/public/test/vicuna-7b-v1.5/') - model = transformers.LlamaForCausalLM(config) - print(model) \ No newline at end of file diff --git a/q_align/model/modeling_mplug_owl2.py b/q_align/model/modeling_mplug_owl2.py deleted file mode 100644 index e7154a67c056cfa4cdd5033b5ce46c5b62bf3cbb..0000000000000000000000000000000000000000 --- a/q_align/model/modeling_mplug_owl2.py +++ /dev/null @@ -1,329 +0,0 @@ -# Copyright 2023 Haotian Liu & Qinghao Ye (Modified from LLaVA) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from typing import List, Optional, Tuple, Union - -import torch -import torch.nn as nn -from torch.nn import CrossEntropyLoss - -from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM -from transformers.modeling_outputs import CausalLMOutputWithPast - -from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig -from .visual_encoder import MplugOwlVisionModel, MplugOwlVisualAbstractorModel -from .modeling_llama2 import replace_llama_modality_adaptive -from q_align.constants import IMAGE_TOKEN_INDEX, IGNORE_INDEX -from icecream import ic - -class MPLUGOwl2MetaModel: - def __init__(self, config): - super(MPLUGOwl2MetaModel, self).__init__(config) - self.vision_model = MplugOwlVisionModel( - MplugOwlVisionConfig(**config.visual_config["visual_model"]) - ) - self.visual_abstractor = MplugOwlVisualAbstractorModel( - MplugOwlVisualAbstractorConfig(**config.visual_config["visual_abstractor"]), config.hidden_size - ) - - def get_vision_tower(self): - vision_model = getattr(self, 'vision_model', None) - if type(vision_model) is list: - vision_model = vision_model[0] - return vision_model - - def get_visual_abstractor(self): - visual_abstractor = getattr(self, 'visual_abstractor', None) - if type(visual_abstractor) is list: - visual_abstractor = visual_abstractor[0] - return visual_abstractor - - -class MPLUGOwl2MetaForCausalLM(ABC): - @abstractmethod - def get_model(self): - pass - - def encode_images(self, images): - image_features = self.get_model().vision_model(images).last_hidden_state - image_features = self.get_model().visual_abstractor(encoder_hidden_states=image_features).last_hidden_state - return image_features - - def prepare_inputs_labels_for_multimodal( - self, input_ids, attention_mask, past_key_values, labels, images - ): - if images is None or input_ids.shape[1] == 1: - if past_key_values is not None and images is not None and input_ids.shape[1] == 1: - attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device) - multiway_indices = torch.zeros_like(input_ids).long().to(self.device) - return input_ids, multiway_indices, attention_mask, past_key_values, None, labels - - if type(images) is list or images.ndim == 5: - concat_images = torch.cat([image for image in images], dim=0) - image_features = self.encode_images(concat_images) - split_sizes = [image.shape[0] for image in images] - image_features = torch.split(image_features, split_sizes, dim=0) - image_features = [x.flatten(0, 1) for x in image_features] - else: - image_features = self.encode_images(images) - - new_input_embeds = [] - new_modality_indicators = [] - new_labels = [] if labels is not None else None - cur_image_idx = 0 - for batch_idx, cur_input_ids in enumerate(input_ids): - if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: - # multimodal LLM, but the current sample is not multimodal - # FIXME: this is a hacky fix, for deepspeed zero3 to work - half_len = cur_input_ids.shape[0] // 2 - cur_image_features = image_features[cur_image_idx] - cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len]) - cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:]) - cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0) - new_input_embeds.append(cur_input_embeds) - - cur_modality_indicators = torch.zeros(len(cur_input_embeds)).long().to(self.device) - new_modality_indicators.append(cur_modality_indicators) - if labels is not None: - new_labels.append(labels[batch_idx]) - cur_image_idx += 1 - continue - image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] - cur_new_input_embeds = [] - cur_modality_indicators = [] - if labels is not None: - cur_labels = labels[batch_idx] - cur_new_labels = [] - assert cur_labels.shape == cur_input_ids.shape - while image_token_indices.numel() > 0: - cur_image_features = image_features[cur_image_idx] - image_token_start = image_token_indices[0] - cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start])) - cur_new_input_embeds.append(cur_image_features) - - # Add modality indicator - assert image_token_start == len(cur_input_ids[:image_token_start]) - cur_modality_indicators.append(torch.zeros(len(cur_input_ids[:image_token_start])).long()) - cur_modality_indicators.append(torch.ones(len(cur_image_features)).long()) - - if labels is not None: - cur_new_labels.append(cur_labels[:image_token_start]) - cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) - cur_labels = cur_labels[image_token_start+1:] - cur_image_idx += 1 - cur_input_ids = cur_input_ids[image_token_start+1:] - image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] - if cur_input_ids.numel() > 0: - cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids)) - cur_modality_indicators.append(torch.zeros(len(cur_input_ids)).long()) - if labels is not None: - cur_new_labels.append(cur_labels) - cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds] - cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0) - new_input_embeds.append(cur_new_input_embeds) - - # Modality - cur_modality_indicators = [x.to(device=self.device) for x in cur_modality_indicators] - cur_modality_indicators = torch.cat(cur_modality_indicators, dim=0) - new_modality_indicators.append(cur_modality_indicators) - - - if labels is not None: - cur_new_labels = torch.cat(cur_new_labels, dim=0) - new_labels.append(cur_new_labels) - - if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds): - max_len = max(x.shape[0] for x in new_input_embeds) - - # Embedding - new_input_embeds_align = [] - for cur_new_embed in new_input_embeds: - cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0) - new_input_embeds_align.append(cur_new_embed) - new_input_embeds = torch.stack(new_input_embeds_align, dim=0) - - # Modality - new_modality_indicators_align = [] - for cur_modality_indicator in new_modality_indicators: - cur_new_embed = torch.cat((cur_modality_indicator, torch.zeros(max_len - cur_modality_indicator.shape[0], dtype=cur_modality_indicator.dtype, device=cur_modality_indicator.device)), dim=0) - new_modality_indicators_align.append(cur_new_embed) - new_modality_indicators = torch.stack(new_modality_indicators_align, dim=0) - - # Label - if labels is not None: - new_labels_align = [] - _new_labels = new_labels - for cur_new_label in new_labels: - cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0) - new_labels_align.append(cur_new_label) - new_labels = torch.stack(new_labels_align, dim=0) - - # Attention Mask - if attention_mask is not None: - new_attention_mask = [] - for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels): - new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device) - new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device) - cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0) - new_attention_mask.append(cur_new_attention_mask) - attention_mask = torch.stack(new_attention_mask, dim=0) - assert attention_mask.shape == new_labels.shape - else: - new_input_embeds = torch.stack(new_input_embeds, dim=0) - new_modality_indicators = torch.stack(new_modality_indicators, dim=0) - if labels is not None: - new_labels = torch.stack(new_labels, dim=0) - - if attention_mask is not None: - new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device) - attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1) - assert attention_mask.shape == new_input_embeds.shape[:2] - return None, new_modality_indicators, attention_mask, past_key_values, new_input_embeds, new_labels - - - -class MPLUGOwl2LlamaModel(MPLUGOwl2MetaModel, LlamaModel): - config_class = MPLUGOwl2Config - - def __init__(self, config: MPLUGOwl2Config): - super(MPLUGOwl2LlamaModel, self).__init__(config) - - -class MPLUGOwl2LlamaForCausalLM(LlamaForCausalLM, MPLUGOwl2MetaForCausalLM): - config_class = MPLUGOwl2Config - - def __init__(self, config): - super(LlamaForCausalLM, self).__init__(config) - self.model = MPLUGOwl2LlamaModel(config) - - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - - # Initialize weights and apply final processing - self.post_init() - - def get_model(self): - return self.model - - def forward( - self, - input_ids: torch.LongTensor = None, - # modality_indicators: torch.LongTensor = None, - attention_mask: Optional[torch.Tensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - images: Optional[torch.FloatTensor] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, CausalLMOutputWithPast]: - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \ - self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) - - # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) - outputs = self.model( - input_ids=input_ids, - modality_indicators=modality_indicators, - attention_mask=attention_mask, - past_key_values=past_key_values, - inputs_embeds=inputs_embeds, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict - ) - - hidden_states = outputs[0] - logits = self.lm_head(hidden_states) - - loss = None - if labels is not None: - # Shift so that tokens < n predict n - shift_logits = logits[..., :-1, :].contiguous() - shift_labels = labels[..., 1:].contiguous() - # Flatten the tokens - loss_fct = CrossEntropyLoss() - shift_logits = shift_logits.view(-1, self.config.vocab_size) - shift_labels = shift_labels.view(-1) - # Enable model/pipeline parallelism - shift_labels = shift_labels.to(shift_logits.device) - loss = loss_fct(shift_logits, shift_labels) - - if not return_dict: - output = (logits,) + outputs[1:] - return (loss,) + output if loss is not None else output - - return CausalLMOutputWithPast( - loss=loss, - logits=logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - - def prepare_inputs_for_generation( - self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs - ): - if past_key_values: - input_ids = input_ids[:, -1:] - - # if `inputs_embeds` are passed, we only want to use them in the 1st generation step - if inputs_embeds is not None and past_key_values is None: - model_inputs = {"inputs_embeds": inputs_embeds} - else: - model_inputs = {"input_ids": input_ids} - - model_inputs.update( - { - "past_key_values": past_key_values, - "use_cache": kwargs.get("use_cache"), - "attention_mask": attention_mask, - "images": kwargs.get("images", None), - } - ) - return model_inputs - -AutoConfig.register("mplug_owl2", MPLUGOwl2Config) -AutoModelForCausalLM.register(MPLUGOwl2Config, MPLUGOwl2LlamaForCausalLM) - -replace_llama_modality_adaptive() - -if __name__ == "__main__": - config = MPLUGOwl2Config.from_pretrained('/cpfs01/shared/public/test/vicuna-7b-v1.5/') - from icecream import ic - # config = MPLUGOwl2Config() - model = MPLUGOwl2LlamaForCausalLM(config) - - images = torch.randn(2, 3, 448, 448) - input_ids = torch.cat([ - torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long() - ], dim=0).unsqueeze(0) - labels = input_ids.clone() - labels[labels < 0] = -100 - - # image_feature = model.encode_images(images) - # ic(image_feature.shape) - - output = model(images=images, input_ids=input_ids, labels=labels) - ic(output.loss) - ic(output.logits.shape) - - model.save_pretrained('/cpfs01/shared/public/test/tmp_owl') \ No newline at end of file diff --git a/q_align/model/utils.py b/q_align/model/utils.py deleted file mode 100644 index 6a47edb191f0f6587827cfab6a731ec106a523b0..0000000000000000000000000000000000000000 --- a/q_align/model/utils.py +++ /dev/null @@ -1,20 +0,0 @@ -from transformers import AutoConfig - - -def auto_upgrade(config): - cfg = AutoConfig.from_pretrained(config) - if 'mplug_owl2' in config and 'mplug_owl2' not in cfg.model_type: - assert cfg.model_type == 'mplug_owl2' - print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.") - print("You must upgrade the checkpoint to the new code base (this can be done automatically).") - confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]") - if confirm.lower() in ["y", "yes"]: - print("Upgrading checkpoint...") - assert len(cfg.architectures) == 1 - setattr(cfg.__class__, "model_type", "mplug_owl2") - cfg.architectures[0] = 'LlavaLlamaForCausalLM' - cfg.save_pretrained(config) - print("Checkpoint upgraded.") - else: - print("Checkpoint upgrade aborted.") - exit(1) \ No newline at end of file diff --git a/q_align/model/visual_encoder.py b/q_align/model/visual_encoder.py deleted file mode 100644 index 39f76207dd9a25f870c1cf35f7fbcba2bf342e0c..0000000000000000000000000000000000000000 --- a/q_align/model/visual_encoder.py +++ /dev/null @@ -1,928 +0,0 @@ -import math -from typing import Any, Optional, Tuple, Union - -from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions -from transformers.modeling_utils import PreTrainedModel -from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer - -import numpy as np -import torch -import torch.nn as nn -import torch.utils.checkpoint -from icecream import ic - -def get_abs_pos(abs_pos, tgt_size): - # abs_pos: L, C - # tgt_size: M - # return: M, C - src_size = int(math.sqrt(abs_pos.size(0))) - tgt_size = int(math.sqrt(tgt_size)) - dtype = abs_pos.dtype - - if src_size != tgt_size: - return F.interpolate( - abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2), - size=(tgt_size, tgt_size), - mode="bicubic", - align_corners=False, - ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype) - else: - return abs_pos - -# https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20 -def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): - """ - grid_size: int of the grid height and width - return: - pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) - """ - grid_h = np.arange(grid_size, dtype=np.float32) - grid_w = np.arange(grid_size, dtype=np.float32) - grid = np.meshgrid(grid_w, grid_h) # here w goes first - grid = np.stack(grid, axis=0) - - grid = grid.reshape([2, 1, grid_size, grid_size]) - pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) - if cls_token: - pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) - return pos_embed - - -def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): - assert embed_dim % 2 == 0 - - # use half of dimensions to encode grid_h - emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) - emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) - - emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) - return emb - - -def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): - """ - embed_dim: output dimension for each position - pos: a list of positions to be encoded: size (M,) - out: (M, D) - """ - assert embed_dim % 2 == 0 - omega = np.arange(embed_dim // 2, dtype=np.float32) - omega /= embed_dim / 2. - omega = 1. / 10000**omega # (D/2,) - - pos = pos.reshape(-1) # (M,) - out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product - - emb_sin = np.sin(out) # (M, D/2) - emb_cos = np.cos(out) # (M, D/2) - - emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) - return emb - - - -class MplugOwlVisionEmbeddings(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.hidden_size = config.hidden_size - self.image_size = config.image_size - self.patch_size = config.patch_size - - self.cls_token = nn.Parameter(torch.randn(1, 1, self.hidden_size)) - - self.patch_embed = nn.Conv2d( - in_channels=3, - out_channels=self.hidden_size, - kernel_size=self.patch_size, - stride=self.patch_size, - bias=False, - ) - - self.num_patches = (self.image_size // self.patch_size) ** 2 - - self.position_embedding = nn.Parameter(torch.randn(1, self.num_patches + 1, self.hidden_size)) - - self.pre_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) - - def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor: - batch_size = pixel_values.size(0) - image_embeds = self.patch_embed(pixel_values) - image_embeds = image_embeds.flatten(2).transpose(1, 2) - - class_embeds = self.cls_token.expand(batch_size, 1, -1).to(image_embeds.dtype) - embeddings = torch.cat([class_embeds, image_embeds], dim=1) - embeddings = embeddings + self.position_embedding[:, : embeddings.size(1)].to(image_embeds.dtype) - embeddings = self.pre_layernorm(embeddings) - return embeddings - - - -class MplugOwlVisionAttention(nn.Module): - """Multi-headed attention from 'Attention Is All You Need' paper""" - - def __init__(self, config): - super().__init__() - self.config = config - self.hidden_size = config.hidden_size - self.num_heads = config.num_attention_heads - self.head_dim = self.hidden_size // self.num_heads - if self.head_dim * self.num_heads != self.hidden_size: - raise ValueError( - f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:" - f" {self.num_heads})." - ) - self.scale = self.head_dim**-0.5 - self.dropout = nn.Dropout(config.attention_dropout) - - self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size) - self.dense = nn.Linear(self.hidden_size, self.hidden_size) - - def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): - return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() - - def forward( - self, - hidden_states: torch.Tensor, - head_mask: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = False, - ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - """Input shape: Batch x Time x Channel""" - - bsz, seq_len, embed_dim = hidden_states.size() - - mixed_qkv = self.query_key_value(hidden_states) - - mixed_qkv = mixed_qkv.reshape(bsz, seq_len, self.num_heads, 3, embed_dim // self.num_heads).permute( - 3, 0, 2, 1, 4 - ) # [3, b, np, sq, hn] - query_states, key_states, value_states = ( - mixed_qkv[0], - mixed_qkv[1], - mixed_qkv[2], - ) - # if self.config.use_flash_attn and flash_attn_func is not None: - if False: - # [b*sq, np, hn] - query_states = query_states.permute(0, 2, 1, 3).contiguous() - query_states = query_states.view(query_states.size(0) * query_states.size(1), query_states.size(2), -1) - - key_states = key_states.permute(0, 2, 1, 3).contiguous() - key_states = key_states.view(key_states.size(0) * key_states.size(1), key_states.size(2), -1) - - value_states = value_states.permute(0, 2, 1, 3).contiguous() - value_states = value_states.view(value_states.size(0) * value_states.size(1), value_states.size(2), -1) - - cu_seqlens = torch.arange( - 0, (bsz + 1) * seq_len, step=seq_len, dtype=torch.int32, device=query_states.device - ) - - context_layer = flash_attn_func( - query_states, - key_states, - value_states, - cu_seqlens, - cu_seqlens, - seq_len, - seq_len, - self.dropout if self.training else 0.0, - softmax_scale=self.scale, - causal=False, - return_attn_probs=False, - ) - # [b*sq, np, hn] => [b, sq, np, hn] - context_layer = context_layer.view(bsz, seq_len, context_layer.size(1), context_layer.size(2)) - else: - # Take the dot product between "query" and "key" to get the raw attention scores. - attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2)) - - attention_scores = attention_scores * self.scale - - # Normalize the attention scores to probabilities. - attention_probs = torch.softmax(attention_scores, dim=-1) - - # This is actually dropping out entire tokens to attend to, which might - # seem a bit unusual, but is taken from the original Transformer paper. - attention_probs = self.dropout(attention_probs) - - # Mask heads if we want to - if head_mask is not None: - attention_probs = attention_probs * head_mask - - context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3) - - new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size,) - context_layer = context_layer.reshape(new_context_layer_shape) - - output = self.dense(context_layer) - - outputs = (output, attention_probs) if output_attentions else (output, None) - - return outputs - - -class QuickGELU(nn.Module): - def forward(self, x: torch.Tensor): - return x * torch.sigmoid(1.702 * x) - - -class MplugOwlMLP(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.activation_fn = QuickGELU() - self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) - self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) - - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - hidden_states = self.fc1(hidden_states) - hidden_states = self.activation_fn(hidden_states) - hidden_states = self.fc2(hidden_states) - return hidden_states - - -class MplugOwlVisionEncoderLayer(nn.Module): - def __init__(self, config): - super().__init__() - self.hidden_size = config.hidden_size - self.self_attn = MplugOwlVisionAttention(config) - self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) - self.mlp = MplugOwlMLP(config) - self.post_attention_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) - - def forward( - self, - hidden_states: torch.Tensor, - attention_mask: torch.Tensor, - output_attentions: Optional[bool] = False, - ) -> Tuple[torch.FloatTensor]: - """ - Args: - hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` - attention_mask (`torch.FloatTensor`): attention mask of size - `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. - `(config.encoder_attention_heads,)`. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - """ - residual = hidden_states - - hidden_states = self.input_layernorm(hidden_states) - hidden_states, attn_weights = self.self_attn( - hidden_states=hidden_states, - head_mask=attention_mask, - output_attentions=output_attentions, - ) - hidden_states = hidden_states + residual - residual = hidden_states - hidden_states = self.post_attention_layernorm(hidden_states) - hidden_states = self.mlp(hidden_states) - - hidden_states = hidden_states + residual - - outputs = (hidden_states,) - - if output_attentions: - outputs += (attn_weights,) - - return outputs - - -class MplugOwlVisionEncoder(nn.Module): - """ - Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a - [`MplugOwlVisionEncoderLayer`]. - - Args: - config (`MplugOwlVisionConfig`): - The corresponding vision configuration for the `MplugOwlEncoder`. - """ - - def __init__(self, config): - super().__init__() - self.config = config - self.layers = nn.ModuleList([MplugOwlVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) - self.gradient_checkpointing = True - - def forward( - self, - inputs_embeds, - attention_mask: Optional[torch.Tensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutput]: - r""" - Args: - inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): - Embedded representation of the inputs. Should be float, not int tokens. - attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors - for more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - encoder_states = () if output_hidden_states else None - all_attentions = () if output_attentions else None - - hidden_states = inputs_embeds - for idx, encoder_layer in enumerate(self.layers): - if output_hidden_states: - encoder_states = encoder_states + (hidden_states,) - if self.gradient_checkpointing and self.training: - - def create_custom_forward(module): - def custom_forward(*inputs): - return module(*inputs, output_attentions) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(encoder_layer), - hidden_states, - attention_mask, - ) - else: - layer_outputs = encoder_layer( - hidden_states, - attention_mask, - output_attentions=output_attentions, - ) - - hidden_states = layer_outputs[0] - - if output_attentions: - all_attentions = all_attentions + (layer_outputs[1],) - - if output_hidden_states: - encoder_states = encoder_states + (hidden_states,) - - if not return_dict: - return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) - return BaseModelOutput( - last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions - ) - - -class MplugOwlVisionModel(PreTrainedModel): - main_input_name = "pixel_values" - - def __init__(self, config): - super().__init__(config) - self.config = config - self.hidden_size = config.hidden_size - - self.embeddings = MplugOwlVisionEmbeddings(config) - self.encoder = MplugOwlVisionEncoder(config) - self.post_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) - - self.post_init() - - - def forward( - self, - pixel_values: Optional[torch.FloatTensor] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPooling]: - r""" - Returns: - - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - if pixel_values is None: - raise ValueError("You have to specify pixel_values") - - hidden_states = self.embeddings(pixel_values) - - encoder_outputs = self.encoder( - inputs_embeds=hidden_states, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - last_hidden_state = encoder_outputs[0] - last_hidden_state = self.post_layernorm(last_hidden_state) - - pooled_output = last_hidden_state[:, 0, :] - pooled_output = self.post_layernorm(pooled_output) - - if not return_dict: - return (last_hidden_state, pooled_output) + encoder_outputs[1:] - - return BaseModelOutputWithPooling( - last_hidden_state=last_hidden_state, - pooler_output=pooled_output, - hidden_states=encoder_outputs.hidden_states, - attentions=encoder_outputs.attentions, - ) - - def get_input_embeddings(self): - return self.embeddings - - -class MplugOwlVisualAbstractorMLP(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - in_features = config.hidden_size - self.act = nn.SiLU() - - self.w1 = nn.Linear(in_features, config.intermediate_size) - self.w2 = nn.Linear(config.intermediate_size, in_features) - self.w3 = nn.Linear(in_features, config.intermediate_size) - self.ffn_ln = nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps) - - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - hidden_states = self.act(self.w1(hidden_states)) * self.w3(hidden_states) - hidden_states = self.ffn_ln(hidden_states) - hidden_states = self.w2(hidden_states) - return hidden_states - - -class MplugOwlVisualAbstractorMultiHeadAttention(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - if config.hidden_size % config.num_attention_heads != 0: - raise ValueError( - "The hidden size (%d) is not a multiple of the number of attention heads (%d)" - % (config.hidden_size, config.num_attention_heads) - ) - - self.num_attention_heads = config.num_attention_heads - self.attention_head_size = int(config.hidden_size / config.num_attention_heads) - self.all_head_size = self.num_attention_heads * self.attention_head_size - - self.query = nn.Linear(config.hidden_size, self.all_head_size) - self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size) - self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size) - - self.dropout = nn.Dropout(config.attention_probs_dropout_prob) - self.save_attention = False - -# self.q_pos_embed = nn.Parameter( -# torch.from_numpy(get_1d_sincos_pos_embed_from_grid(config.hidden_size, np.arange(config.num_learnable_queries, dtype=np.float32))).float() -# ).requires_grad_(False) -# grids = config.grid_size -# self.k_pos_embed = nn.Parameter( -# torch.from_numpy(get_2d_sincos_pos_embed(config.hidden_size, grids, cls_token=True)).float() -# ).requires_grad_(False) - grids = config.grid_size - self.register_buffer( - 'q_pos_embed', - torch.from_numpy(get_1d_sincos_pos_embed_from_grid(config.hidden_size, np.arange(config.num_learnable_queries, dtype=np.float32))).float() - ) - self.register_buffer( - 'k_pos_embed', - torch.from_numpy(get_2d_sincos_pos_embed(config.hidden_size, grids, cls_token=True)).float() - ) - - - def save_attn_gradients(self, attn_gradients): - self.attn_gradients = attn_gradients - - def get_attn_gradients(self): - return self.attn_gradients - - def save_attention_map(self, attention_map): - self.attention_map = attention_map - - def get_attention_map(self): - return self.attention_map - - def transpose_for_scores(self, x): - new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) - x = x.view(*new_x_shape) - return x.permute(0, 2, 1, 3) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - ): - # If this is instantiated as a cross-attention module, the keys - # and values come from an encoder; the attention mask needs to be - # such that the encoder's padding tokens are not attended to. - - qk_pos_embed = torch.cat([self.q_pos_embed, self.k_pos_embed], dim = 0).unsqueeze(0).to(dtype=hidden_states.dtype) - - key_layer = self.transpose_for_scores(self.key(encoder_hidden_states + qk_pos_embed)) - value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) - attention_mask = encoder_attention_mask - - mixed_query_layer = self.query(hidden_states + self.q_pos_embed.unsqueeze(0).to(dtype=hidden_states.dtype)) - - query_layer = self.transpose_for_scores(mixed_query_layer) - - past_key_value = (key_layer, value_layer) - - # Take the dot product between "query" and "key" to get the raw attention scores. - attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) - - attention_scores = attention_scores / math.sqrt(self.attention_head_size) - - if attention_mask is not None: - # Apply the attention mask is (precomputed for all layers in BertModel forward() function) - attention_scores = attention_scores + attention_mask - - # Normalize the attention scores to probabilities. - attention_probs = nn.Softmax(dim=-1)(attention_scores) - - if self.save_attention: - self.save_attention_map(attention_probs) - attention_probs.register_hook(self.save_attn_gradients) - - # This is actually dropping out entire tokens to attend to, which might - # seem a bit unusual, but is taken from the original Transformer paper. - attention_probs_dropped = self.dropout(attention_probs) - - # Mask heads if we want to - if head_mask is not None: - attention_probs_dropped = attention_probs_dropped * head_mask - - context_layer = torch.matmul(attention_probs_dropped, value_layer) - - context_layer = context_layer.permute(0, 2, 1, 3).contiguous() - new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) - context_layer = context_layer.view(*new_context_layer_shape) - - outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) - - outputs = outputs + (past_key_value,) - return outputs - - -class MplugOwlVisualAbstractorCrossOutput(nn.Module): - def __init__(self, config): - super().__init__() - dim = config.hidden_size - self.out_proj = nn.Linear(dim, dim, bias=True) - self.norm2 = nn.LayerNorm(dim) - self.mlp = MplugOwlVisualAbstractorMLP(config) - - def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: - input_tensor = input_tensor + self.out_proj(hidden_states) - input_tensor = input_tensor + self.mlp(self.norm2(input_tensor)) - return input_tensor - - -class MplugOwlVisualAbstractorAttention(nn.Module): - def __init__(self, config): - super().__init__() - self.attention = MplugOwlVisualAbstractorMultiHeadAttention(config) - self.output = MplugOwlVisualAbstractorCrossOutput(config) - self.pruned_heads = set() - self.norm1 = nn.LayerNorm(config.hidden_size) - self.normk = nn.LayerNorm(config.hidden_size) - - def prune_heads(self, heads): - if len(heads) == 0: - return - heads, index = find_pruneable_heads_and_indices( - heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads - ) - - # Prune linear layers - self.attention.query = prune_linear_layer(self.attention.query, index) - self.attention.key = prune_linear_layer(self.attention.key, index) - self.attention.value = prune_linear_layer(self.attention.value, index) - self.output.dense = prune_linear_layer(self.output.out_proj, index, dim=1) - - # Update hyper params and store pruned heads - self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads) - self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads - self.pruned_heads = self.pruned_heads.union(heads) - - def forward( - self, - hidden_states: torch.Tensor, - attention_mask: Optional[torch.FloatTensor] = None, - head_mask: Optional[torch.FloatTensor] = None, - encoder_hidden_states: Optional[torch.FloatTensor] = None, - encoder_attention_mask: Optional[torch.FloatTensor] = None, - past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, - output_attentions: Optional[bool] = False, - ) -> Tuple[torch.Tensor]: - # HACK we apply norm on q and k - hidden_states = self.norm1(hidden_states) - encoder_hidden_states = self.normk(encoder_hidden_states) - encoder_hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1) - encoder_attention_mask = torch.cat([attention_mask, encoder_attention_mask], dim=-1) - self_outputs = self.attention( - hidden_states, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - past_key_value, - output_attentions, - ) - attention_output = self.output(self_outputs[0], hidden_states) - # add attentions if we output them - outputs = (attention_output,) + self_outputs[1:] - return outputs - - -class MplugOwlVisualAbstractorLayer(nn.Module): - def __init__(self, config, layer_idx): - super().__init__() - self.chunk_size_feed_forward = config.chunk_size_feed_forward - self.seq_len_dim = 1 - - self.layer_idx = layer_idx - - self.crossattention = MplugOwlVisualAbstractorAttention(config) - self.has_cross_attention = True - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - output_attentions=False, - ): - if encoder_hidden_states is None: - raise ValueError("encoder_hidden_states must be given for cross-attention layers") - cross_attention_outputs = self.crossattention( - hidden_states, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - output_attentions=output_attentions, - ) - query_attention_output = cross_attention_outputs[0] - - outputs = (query_attention_output,) - return outputs - - -class MplugOwlVisualAbstractorEncoder(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.layers = nn.ModuleList( - [MplugOwlVisualAbstractorLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] - ) - self.gradient_checkpointing = True - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - output_attentions=False, - output_hidden_states=False, - return_dict=True, - ): - all_hidden_states = () if output_hidden_states else None - - for i in range(self.config.num_hidden_layers): - layer_module = self.layers[i] - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - layer_head_mask = head_mask[i] if head_mask is not None else None - past_key_value = past_key_values[i] if past_key_values is not None else None - - if getattr(self.config, "gradient_checkpointing", False) and self.training: - - def create_custom_forward(module): - def custom_forward(*inputs): - return module(*inputs, past_key_value, output_attentions) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(layer_module), - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - ) - else: - layer_outputs = layer_module( - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - output_attentions, - ) - - hidden_states = layer_outputs[0] - - return BaseModelOutput( - last_hidden_state=hidden_states, - ) - - -class MplugOwlVisualAbstractorModel(PreTrainedModel): - def __init__(self, config, language_hidden_size): - super().__init__(config) - self.config = config - - self.encoder = MplugOwlVisualAbstractorEncoder(config) - self.visual_fc = torch.nn.Linear(config.hidden_size, language_hidden_size) - self.query_embeds = torch.nn.Parameter(torch.randn(1, config.num_learnable_queries, config.hidden_size)) - self.vit_eos = torch.nn.Parameter(torch.randn(1, 1, language_hidden_size)) - - self.post_init() - - def _prune_heads(self, heads_to_prune): - """ - Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base - class PreTrainedModel - """ - for layer, heads in heads_to_prune.items(): - self.encoder.layer[layer].attention.prune_heads(heads) - - def get_extended_attention_mask( - self, - attention_mask: torch.Tensor, - input_shape: Tuple[int], - device: torch.device, - ) -> torch.Tensor: - """ - Makes broadcastable attention and causal masks so that future and masked tokens are ignored. - - Arguments: - attention_mask (`torch.Tensor`): - Mask with ones indicating tokens to attend to, zeros for tokens to ignore. - input_shape (`Tuple[int]`): - The shape of the input to the model. - device: (`torch.device`): - The device of the input to the model. - - Returns: - `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`. - """ - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if attention_mask.dim() == 3: - extended_attention_mask = attention_mask[:, None, :, :] - elif attention_mask.dim() == 2: - # Provided a padding mask of dimensions [batch_size, seq_length] - # - the model is an encoder, so make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] - extended_attention_mask = attention_mask[:, None, None, :] - else: - raise ValueError( - "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( - input_shape, attention_mask.shape - ) - ) - - # Since attention_mask is 1.0 for positions we want to attend and 0.0 for - # masked positions, this operation will create a tensor which is 0.0 for - # positions we want to attend and -10000.0 for masked positions. - # Since we are adding it to the raw scores before the softmax, this is - # effectively the same as removing these entirely. - extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility - extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 - return extended_attention_mask - - def forward( - self, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - ): - r""" - encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, `optional`): - Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if - the model is configured as a decoder. - encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): - Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in - the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of: - shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and - value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are - used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key - value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape - `(batch_size, sequence_length)`. - """ - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - query_embeds = self.query_embeds.repeat(encoder_hidden_states.shape[0], 1, 1) - embedding_output = query_embeds - input_shape = embedding_output.size()[:-1] - batch_size, seq_length = input_shape - device = embedding_output.device - - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if attention_mask is None: - attention_mask = torch.ones( - (query_embeds.shape[0], query_embeds.shape[1]), dtype=torch.long, device=query_embeds.device - ) - extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device) - - # If a 2D or 3D attention mask is provided for the cross-attention - # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] - if encoder_hidden_states is not None: - if type(encoder_hidden_states) == list: - encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() - else: - ( - encoder_batch_size, - encoder_sequence_length, - _, - ) = encoder_hidden_states.size() - encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) - - if type(encoder_attention_mask) == list: - encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] - elif encoder_attention_mask is None: - encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) - encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) - else: - encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) - else: - encoder_extended_attention_mask = None - - # Prepare head mask if needed - # 1.0 in head_mask indicate we keep the head - # attention_probs has shape bsz x n_heads x N x N - # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] - # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] - head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) - - encoder_outputs = self.encoder( - embedding_output, - attention_mask=extended_attention_mask, - head_mask=head_mask, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_extended_attention_mask, - past_key_values=past_key_values, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - sequence_output = encoder_outputs[0] - pooled_output = sequence_output[:, 0, :] - - sequence_output = self.visual_fc(sequence_output) - sequence_output = torch.cat([sequence_output, self.vit_eos.repeat(sequence_output.shape[0], 1, 1)], dim=1) - - return BaseModelOutputWithPooling( - last_hidden_state=sequence_output, - pooler_output=pooled_output, - hidden_states=encoder_outputs.hidden_states, - ) - - -if __name__ == "__main__": - from configuration_mplug_owl2 import MPLUGOwl2Config - config = MPLUGOwl2Config() - visual_model = MplugOwlVisionModel(config.visual_config["visual_model"]) - print(visual_model) - - abstractor_module = MplugOwlVisualAbstractorModel(config.visual_config["visual_abstractor"], config.hidden_size) - print(abstractor_module) \ No newline at end of file diff --git a/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-310.pyc b/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-310.pyc deleted file mode 100644 index 526270d58a01315bbdac70f4465e54e94d0335c9..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-310.pyc and /dev/null differ diff --git a/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-311.pyc b/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-311.pyc deleted file mode 100644 index 9d2b77240124a91ac5f378a6b3997814f71b03ae..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/llama_flash_attn_monkey_patch.cpython-311.pyc and /dev/null differ diff --git a/q_align/train/__pycache__/mplug_owl2_trainer.cpython-310.pyc b/q_align/train/__pycache__/mplug_owl2_trainer.cpython-310.pyc deleted file mode 100644 index cb851af86edcd4279750449e470b5ed757f54d38..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/mplug_owl2_trainer.cpython-310.pyc and /dev/null differ diff --git a/q_align/train/__pycache__/mplug_owl2_trainer.cpython-311.pyc b/q_align/train/__pycache__/mplug_owl2_trainer.cpython-311.pyc deleted file mode 100644 index b9d7423b8c38926885b9376550027174522827c0..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/mplug_owl2_trainer.cpython-311.pyc and /dev/null differ diff --git a/q_align/train/__pycache__/train.cpython-310.pyc b/q_align/train/__pycache__/train.cpython-310.pyc deleted file mode 100644 index 1cc4f452551034733cf2096054fa152b0f490de0..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/train.cpython-310.pyc and /dev/null differ diff --git a/q_align/train/__pycache__/train.cpython-311.pyc b/q_align/train/__pycache__/train.cpython-311.pyc deleted file mode 100644 index 5aa2ed03477cf21175212b9c3dbdf46ee438b267..0000000000000000000000000000000000000000 Binary files a/q_align/train/__pycache__/train.cpython-311.pyc and /dev/null differ diff --git a/q_align/train/llama_flash_attn_monkey_patch.py b/q_align/train/llama_flash_attn_monkey_patch.py deleted file mode 100644 index 23bfdd8920b25581956356ca881f83070e2ae111..0000000000000000000000000000000000000000 --- a/q_align/train/llama_flash_attn_monkey_patch.py +++ /dev/null @@ -1,117 +0,0 @@ -from typing import Optional, Tuple -import warnings - -import torch - -import transformers -from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv - -try: - from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func -except ImportError: - from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func -from flash_attn.bert_padding import unpad_input, pad_input - - -def forward( - self, - hidden_states: torch.Tensor, - modality_indicators: torch.Tensor, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.Tensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: bool = False, - use_cache: bool = False, - padding_mask: bool = None, -) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - if output_attentions: - warnings.warn( - "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead." - ) - - bsz, q_len, _ = hidden_states.size() - - query_states = ( - self.q_proj(hidden_states) - .view(bsz, q_len, self.num_heads, self.head_dim) - .transpose(1, 2) - ) - key_states = ( - self.k_proj(hidden_states, modality_indicators) - .view(bsz, q_len, self.num_key_value_heads, self.head_dim) - .transpose(1, 2) - ) - value_states = ( - self.v_proj(hidden_states, modality_indicators) - .view(bsz, q_len, self.num_key_value_heads, self.head_dim) - .transpose(1, 2) - ) # shape: (b, num_heads, s, head_dim) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - kv_seq_len += past_key_value[0].shape[-2] - - cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb( - query_states, key_states, cos, sin, position_ids - ) - - if past_key_value is not None: - # reuse k, v - key_states = torch.cat([past_key_value[0], key_states], dim=2) - value_states = torch.cat([past_key_value[1], value_states], dim=2) - - past_key_value = (key_states, value_states) if use_cache else None - - # repeat k/v heads if n_kv_heads < n_heads - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) - - # Transform the data into the format required by flash attention - qkv = torch.stack([query_states, key_states, value_states], dim=2) - qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim] - key_padding_mask = attention_mask - - if key_padding_mask is None: - qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim) - cu_q_lens = torch.arange( - 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device - ) - max_s = q_len - output = flash_attn_unpadded_qkvpacked_func( - qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True - ) - output = output.view(bsz, q_len, -1) - else: - qkv = qkv.reshape(bsz, q_len, -1) - qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask) - qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) - output_unpad = flash_attn_unpadded_qkvpacked_func( - qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True - ) - output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim) - output = pad_input(output_unpad, indices, bsz, q_len) - - return self.o_proj(output), None, past_key_value - - -# Disable the transformation of the attention mask in LlamaModel as the flash attention -# requires the attention mask to be the same as the key_padding_mask -def _prepare_decoder_attention_mask( - self, attention_mask, input_shape, inputs_embeds, past_key_values_length -): - # [bsz, seq_len] - return attention_mask - - -def replace_llama_attn_with_flash_attn(): - cuda_major, cuda_minor = torch.cuda.get_device_capability() - if cuda_major < 8: - warnings.warn( - "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." - "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593" - ) - transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = ( - _prepare_decoder_attention_mask - ) - transformers.models.llama.modeling_llama.LlamaAttention.forward = forward \ No newline at end of file diff --git a/q_align/train/mplug_owl2_trainer.py b/q_align/train/mplug_owl2_trainer.py deleted file mode 100644 index 293dcdf21c82c715e663af11b90a19543244af18..0000000000000000000000000000000000000000 --- a/q_align/train/mplug_owl2_trainer.py +++ /dev/null @@ -1,243 +0,0 @@ -import os -import torch - -from torch.utils.data import Sampler - -from transformers import Trainer -from transformers.trainer import ( - is_sagemaker_mp_enabled, - get_parameter_names, - has_length, - ALL_LAYERNORM_LAYERS, - ShardedDDPOption, - logger, -) -from typing import List, Optional -from icecream import ic - -def maybe_zero_3(param, ignore_status=False, name=None): - from deepspeed import zero - from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus - if hasattr(param, "ds_id"): - if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: - if not ignore_status: - print(name, 'no ignore status') - with zero.GatheredParameters([param]): - param = param.data.detach().cpu().clone() - else: - param = param.detach().cpu().clone() - return param - - -def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): - to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} - to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()} - return to_return - - -def split_to_even_chunks(indices, lengths, num_chunks): - """ - Split a list of indices into `chunks` chunks of roughly equal lengths. - """ - - if len(indices) % num_chunks != 0: - return [indices[i::num_chunks] for i in range(num_chunks)] - - num_indices_per_chunk = len(indices) // num_chunks - - chunks = [[] for _ in range(num_chunks)] - chunks_lengths = [0 for _ in range(num_chunks)] - for index in indices: - shortest_chunk = chunks_lengths.index(min(chunks_lengths)) - chunks[shortest_chunk].append(index) - chunks_lengths[shortest_chunk] += lengths[index] - if len(chunks[shortest_chunk]) == num_indices_per_chunk: - chunks_lengths[shortest_chunk] = float("inf") - - return chunks - - -def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None): - # We need to use torch for the random part as a distributed sampler will set the random seed for torch. - assert all(l != 0 for l in lengths), "Should not have zero length." - if all(l > 0 for l in lengths) or all(l < 0 for l in lengths): - # all samples are in the same modality - return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator) - mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0]) - lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0]) - - mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)] - lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)] - megabatch_size = world_size * batch_size - mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)] - lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)] - - last_mm = mm_megabatches[-1] - last_lang = lang_megabatches[-1] - additional_batch = last_mm + last_lang - megabatches = mm_megabatches[:-1] + lang_megabatches[:-1] - megabatch_indices = torch.randperm(len(megabatches), generator=generator) - megabatches = [megabatches[i] for i in megabatch_indices] - - if len(additional_batch) > 0: - megabatches.append(sorted(additional_batch)) - - return [i for megabatch in megabatches for i in megabatch] - - -def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True): - # We need to use torch for the random part as a distributed sampler will set the random seed for torch. - indices = torch.randperm(len(lengths), generator=generator) - megabatch_size = world_size * batch_size - megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] - megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] - megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches] - - return [i for megabatch in megabatches for batch in megabatch for i in batch] - - -class LengthGroupedSampler(Sampler): - r""" - Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while - keeping a bit of randomness. - """ - - def __init__( - self, - batch_size: int, - world_size: int, - lengths: Optional[List[int]] = None, - generator=None, - group_by_modality: bool = False, - ): - if lengths is None: - raise ValueError("Lengths must be provided.") - - self.batch_size = batch_size - self.world_size = world_size - self.lengths = lengths - self.generator = generator - self.group_by_modality = group_by_modality - - def __len__(self): - return len(self.lengths) - - def __iter__(self): - if self.group_by_modality: - indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) - else: - indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) - return iter(indices) - - -class MPLUGOwl2Trainer(Trainer): - - def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: - if self.train_dataset is None or not has_length(self.train_dataset): - return None - - if self.args.group_by_modality_length: - lengths = self.train_dataset.modality_lengths - return LengthGroupedSampler( - self.args.train_batch_size, - world_size=self.args.world_size * self.args.gradient_accumulation_steps, - lengths=lengths, - group_by_modality=True, - ) - else: - return super()._get_train_sampler() - - def create_optimizer(self): - """ - Setup the optimizer. - - We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the - Trainer's init through `optimizers`, or subclass and override this method in a subclass. - """ - if is_sagemaker_mp_enabled(): - return super().create_optimizer() - if self.sharded_ddp == ShardedDDPOption.SIMPLE: - return super().create_optimizer() - - opt_model = self.model - - if self.optimizer is None: - decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS) - decay_parameters = [name for name in decay_parameters if "bias" not in name] - if self.args.visual_abstractor_lr is not None: - projector_parameters = [name for name, _ in opt_model.named_parameters() if "visual_abstractor_lr" in name] - optimizer_grouped_parameters = [ - { - "params": [ - p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in projector_parameters and p.requires_grad) - ], - "weight_decay": self.args.weight_decay, - }, - { - "params": [ - p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in projector_parameters and p.requires_grad) - ], - "weight_decay": 0.0, - }, - { - "params": [ - p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in projector_parameters and p.requires_grad) - ], - "weight_decay": self.args.weight_decay, - "lr": self.args.visual_abstractor_lr, - }, - { - "params": [ - p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in projector_parameters and p.requires_grad) - ], - "weight_decay": 0.0, - "lr": self.args.visual_abstractor_lr, - }, - ] - else: - optimizer_grouped_parameters = [ - { - "params": [ - p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad) - ], - "weight_decay": self.args.weight_decay, - }, - { - "params": [ - p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad) - ], - "weight_decay": 0.0, - }, - ] - ic(len(optimizer_grouped_parameters[0]['params']),len(optimizer_grouped_parameters[1]['params'])) - optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args) - - if self.sharded_ddp == ShardedDDPOption.SIMPLE: - self.optimizer = OSS( - params=optimizer_grouped_parameters, - optim=optimizer_cls, - **optimizer_kwargs, - ) - else: - self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) - if optimizer_cls.__name__ == "Adam8bit": - import bitsandbytes - - manager = bitsandbytes.optim.GlobalOptimManager.get_instance() - - skipped = 0 - for module in opt_model.modules(): - if isinstance(module, nn.Embedding): - skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values()) - logger.info(f"skipped {module}: {skipped/2**20}M params") - manager.register_module_override(module, "weight", {"optim_bits": 32}) - logger.debug(f"bitsandbytes: will optimize {module} in fp32") - logger.info(f"skipped: {skipped/2**20}M params") - - return self.optimizer - - def _save_checkpoint(self, model, trial, metrics=None): - super(MPLUGOwl2Trainer, self)._save_checkpoint(model, trial, metrics) - - def _save(self, output_dir: Optional[str] = None, state_dict=None): - super(MPLUGOwl2Trainer, self)._save(output_dir, state_dict) \ No newline at end of file diff --git a/q_align/train/train.py b/q_align/train/train.py deleted file mode 100644 index d109848b1664625fdf099c50e210e1a93a909002..0000000000000000000000000000000000000000 --- a/q_align/train/train.py +++ /dev/null @@ -1,844 +0,0 @@ -# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: -# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: -# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import copy -from dataclasses import dataclass, field -import json -import logging -import pathlib -from typing import Dict, Optional, Sequence, List - -from PIL import ImageFile -ImageFile.LOAD_TRUNCATED_IMAGES = True - -import torch - -import transformers -from transformers.models.clip.image_processing_clip import CLIPImageProcessor - -from torch.utils.data import Dataset -from q_align.train.mplug_owl2_trainer import MPLUGOwl2Trainer -from q_align.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN - -from q_align import conversation as conversation_lib -from q_align.model import * -from q_align.mm_utils import tokenizer_image_token - -from PIL import Image -from icecream import ic - -local_rank = None - - -def rank0_print(*args): - if local_rank == 0: - print(*args) - - -@dataclass -class ModelArguments: - model_name_or_path: Optional[str] = field(default="facebook/opt-125m") - version: Optional[str] = field(default="v0") - freeze_backbone: bool = field(default=False) - -@dataclass -class DataArguments: - data_path: str = field(default=None, - metadata={"help": "Path to the training data."}) - lazy_preprocess: bool = False - is_multimodal: bool = False - image_folder: Optional[str] = field(default=None) - image_aspect_ratio: str = 'square' - image_grid_pinpoints: Optional[str] = field(default=None) - - -@dataclass -class TrainingArguments(transformers.TrainingArguments): - cache_dir: Optional[str] = field(default=None) - optim: str = field(default="adamw_torch") - remove_unused_columns: bool = field(default=False) - - tune_visual_abstractor: bool = field(default=True) - freeze_vision_model: bool = field(default=True) - - model_max_length: int = field( - default=512, - metadata={ - "help": - "Maximum sequence length. Sequences will be right padded (and possibly truncated)." - }, - ) - double_quant: bool = field( - default=True, - metadata={"help": "Compress the quantization statistics through double quantization."} - ) - quant_type: str = field( - default="nf4", - metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} - ) - bits: int = field( - default=16, - metadata={"help": "How many bits to use."} - ) - lora_enable: bool = False - lora_r: int = 64 - lora_alpha: int = 16 - lora_dropout: float = 0.05 - lora_weight_path: str = "" - lora_bias: str = "none" - visual_abstractor_lr: Optional[float] = None - group_by_modality_length: bool = field(default=False) - - -def maybe_zero_3(param, ignore_status=False, name=None): - from deepspeed import zero - from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus - if hasattr(param, "ds_id"): - if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: - if not ignore_status: - logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") - with zero.GatheredParameters([param]): - param = param.data.detach().cpu().clone() - else: - param = param.detach().cpu().clone() - return param - - -# Borrowed from peft.utils.get_peft_model_state_dict -def get_peft_state_maybe_zero_3(named_params, bias): - if bias == "none": - to_return = {k: t for k, t in named_params if "lora_" in k} - elif bias == "all": - to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} - elif bias == "lora_only": - to_return = {} - maybe_lora_bias = {} - lora_bias_names = set() - for k, t in named_params: - if "lora_" in k: - to_return[k] = t - bias_name = k.split("lora_")[0] + "bias" - lora_bias_names.add(bias_name) - elif "bias" in k: - maybe_lora_bias[k] = t - for k, t in maybe_lora_bias: - if bias_name in lora_bias_names: - to_return[bias_name] = t - else: - raise NotImplementedError - to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} - return to_return - - -def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): - to_return = {k: t for k, t in named_params if "lora_" not in k} - if require_grad_only: - to_return = {k: t for k, t in to_return.items() if t.requires_grad} - to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} - return to_return - - -def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): - to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} - to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} - return to_return - - -def find_all_linear_names(model): - cls = torch.nn.Linear - lora_module_names = set() - multimodal_keywords = ['vision_model', 'visual_abstractor'] - for name, module in model.named_modules(): - if any(mm_keyword in name for mm_keyword in multimodal_keywords): - continue - if isinstance(module, cls): - lora_module_names.add(name) - - if 'lm_head' in lora_module_names: # needed for 16-bit - lora_module_names.remove('lm_head') - return list(lora_module_names) - - -def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, - output_dir: str): - """Collects the state dict and dump to disk.""" - - if trainer.deepspeed: - torch.cuda.synchronize() - trainer.save_model(output_dir) - return - - state_dict = trainer.model.state_dict() - if trainer.args.should_save: - cpu_state_dict = { - key: value.cpu() - for key, value in state_dict.items() - } - del state_dict - trainer._save(output_dir, state_dict=cpu_state_dict) # noqa - - -def smart_tokenizer_and_embedding_resize( - special_tokens_dict: Dict, - tokenizer: transformers.PreTrainedTokenizer, - model: transformers.PreTrainedModel, -): - """Resize tokenizer and embedding. - - Note: This is the unoptimized version that may make your embedding size not be divisible by 64. - """ - num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) - model.resize_token_embeddings(len(tokenizer)) - - if num_new_tokens > 0: - input_embeddings = model.get_input_embeddings().weight.data - output_embeddings = model.get_output_embeddings().weight.data - - input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( - dim=0, keepdim=True) - output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( - dim=0, keepdim=True) - - input_embeddings[-num_new_tokens:] = input_embeddings_avg - output_embeddings[-num_new_tokens:] = output_embeddings_avg - - -def _tokenize_fn(strings: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer) -> Dict: - """Tokenize a list of strings.""" - tokenized_list = [ - tokenizer( - text, - return_tensors="pt", - padding="longest", - max_length=tokenizer.model_max_length, - truncation=True, - ) for text in strings - ] - input_ids = labels = [ - tokenized.input_ids[0] for tokenized in tokenized_list - ] - input_ids_lens = labels_lens = [ - tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() - for tokenized in tokenized_list - ] - return dict( - input_ids=input_ids, - labels=labels, - input_ids_lens=input_ids_lens, - labels_lens=labels_lens, - ) - - -def _mask_targets(target, tokenized_lens, speakers): - # cur_idx = 0 - cur_idx = tokenized_lens[0] - tokenized_lens = tokenized_lens[1:] - target[:cur_idx] = IGNORE_INDEX - for tokenized_len, speaker in zip(tokenized_lens, speakers): - if speaker == "human": - target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX - cur_idx += tokenized_len - - -def _add_speaker_and_signal(header, source, get_conversation=True): - """Add speaker and start/end signal on each round.""" - BEGIN_SIGNAL = "### " - END_SIGNAL = "\n" - conversation = header - for sentence in source: - from_str = sentence["from"] - if from_str.lower() == "human": - from_str = conversation_lib.default_conversation.roles[0] - elif from_str.lower() == "gpt": - from_str = conversation_lib.default_conversation.roles[1] - else: - from_str = 'unknown' - sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + - sentence["value"] + END_SIGNAL) - if get_conversation: - conversation += sentence["value"] - conversation += BEGIN_SIGNAL - return conversation - - -def preprocess_multimodal( - sources: Sequence[str], - data_args: DataArguments -) -> Dict: - is_multimodal = data_args.is_multimodal - if not is_multimodal: - return sources - - for source in sources: - for sentence in source: - if DEFAULT_IMAGE_TOKEN in sentence['value']: - sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() - sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] - sentence['value'] = sentence['value'].strip() - - replace_token = DEFAULT_IMAGE_TOKEN - sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) - - return sources - - -def preprocess_v1( - sources, - tokenizer: transformers.PreTrainedTokenizer, - has_image: bool = False -) -> Dict: - conv = conversation_lib.default_conversation.copy() - roles = {"human": conv.roles[0], "gpt": conv.roles[1]} - - # Apply prompt templates - conversations = [] - for i, source in enumerate(sources): - if roles[source[0]["from"]] != conv.roles[0]: - # Skip the first one if it is not from human - source = source[1:] - - conv.messages = [] - for j, sentence in enumerate(source): - role = roles[sentence["from"]] - assert role == conv.roles[j % 2], f"{i}" - conv.append_message(role, sentence["value"]) - conversations.append(conv.get_prompt()) - - # Tokenize conversations - - if has_image: - input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) - else: - input_ids = tokenizer( - conversations, - return_tensors="pt", - padding="longest", - max_length=tokenizer.model_max_length, - truncation=True, - ).input_ids - - targets = input_ids.clone() - - assert conv.sep_style == conversation_lib.SeparatorStyle.TWO or conv.sep_style == conversation_lib.SeparatorStyle.TWO_NO_SYS - - # Mask targets - sep = conv.sep + conv.roles[1] + ": " - for conversation, target in zip(conversations, targets): - total_len = int(target.ne(tokenizer.pad_token_id).sum()) - - rounds = conversation.split(conv.sep2) - cur_len = 1 - target[:cur_len] = IGNORE_INDEX - for i, rou in enumerate(rounds): - if rou == "": - break - - parts = rou.split(sep) - if len(parts) != 2: - break - parts[0] += sep - - if has_image: - round_len = len(tokenizer_image_token(rou, tokenizer)) - instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 - else: - round_len = len(tokenizer(rou).input_ids) - instruction_len = len(tokenizer(parts[0]).input_ids) - 2 - - target[cur_len : cur_len + instruction_len] = IGNORE_INDEX - - cur_len += round_len - target[cur_len:] = IGNORE_INDEX - - if cur_len < tokenizer.model_max_length: - if cur_len != total_len: - target[:] = IGNORE_INDEX - print( - f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." - f" (ignored)" - ) - - return dict( - input_ids=input_ids, - labels=targets, - ) - - -def preprocess_plain( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, -) -> Dict: - # add end signal and concatenate together - conversations = [] - for source in sources: - assert len(source) == 2 - assert DEFAULT_IMAGE_TOKEN in source[0]['value'] - source[0]['value'] = DEFAULT_IMAGE_TOKEN - conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep - conversations.append(conversation) - # tokenize conversations - input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] - targets = copy.deepcopy(input_ids) - for target, source in zip(targets, sources): - tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) - target[:tokenized_len] = IGNORE_INDEX - - return dict(input_ids=input_ids, labels=targets) - - -def preprocess( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, - has_image: bool = False -) -> Dict: - """ - Given a list of sources, each is a conversation list. This transform: - 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; - 2. Concatenate conversations together; - 3. Tokenize the concatenated conversation; - 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. - """ - if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: - return preprocess_plain(sources, tokenizer) - if conversation_lib.default_conversation.version.startswith("v1"): - return preprocess_v1(sources, tokenizer, has_image=has_image) - # add end signal and concatenate together - conversations = [] - for source in sources: - header = f"{conversation_lib.default_conversation.system}\n\n" - conversation = _add_speaker_and_signal(header, source) - conversations.append(conversation) - # tokenize conversations - def get_tokenize_len(prompts): - return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] - if has_image: - input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] - else: - conversations_tokenized = _tokenize_fn(conversations, tokenizer) - input_ids = conversations_tokenized["input_ids"] - - targets = copy.deepcopy(input_ids) - for target, source in zip(targets, sources): - if has_image: - tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) - else: - tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] - speakers = [sentence["from"] for sentence in source] - _mask_targets(target, tokenized_lens, speakers) - - return dict(input_ids=input_ids, labels=targets) - - -def load_video(video_file): - from decord import VideoReader - vr = VideoReader(video_file) - - # Get video frame rate - fps = vr.get_avg_fps() - - # Calculate frame indices for 1fps - frame_indices = [int(fps * i) for i in range(int(len(vr) / fps))] - frames = vr.get_batch(frame_indices).asnumpy() - return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))] - -def expand2square(pil_img, background_color): - width, height = pil_img.size - if width == height: - return pil_img - elif width > height: - result = Image.new(pil_img.mode, (width, width), background_color) - result.paste(pil_img, (0, (width - height) // 2)) - return result - else: - result = Image.new(pil_img.mode, (height, height), background_color) - result.paste(pil_img, ((height - width) // 2, 0)) - return result - -class LazySupervisedDataset(Dataset): - """Dataset for supervised fine-tuning.""" - - def __init__(self, data_path: str, - tokenizer: transformers.PreTrainedTokenizer, - data_args: DataArguments): - super(LazySupervisedDataset, self).__init__() - list_data_dict = json.load(open(data_path, "r")) - - rank0_print("Formatting inputs...Skip in lazy mode") - self.tokenizer = tokenizer - self.list_data_dict = list_data_dict - self.data_args = data_args - - def __len__(self): - return len(self.list_data_dict) - - @property - def lengths(self): - length_list = [] - for sample in self.list_data_dict: - img_tokens = 128 if 'image' in sample else 0 - length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens) - return length_list - - - @property - def modality_lengths(self): - length_list = [] - for sample in self.list_data_dict: - cur_len = sum(len(conv['value'].split()) for conv in sample['conversations']) - cur_len = cur_len if 'image' in sample else -cur_len - length_list.append(cur_len) - return length_list - -# def __getitem__(self, i) -> Dict[str, torch.Tensor]: -# sources = self.list_data_dict[i] -# if isinstance(i, int): -# sources = [sources] -# assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME -# if 'image' in sources[0]: -# image_file = self.list_data_dict[i]['image'] -# image_folder = self.data_args.image_folder -# processor = self.data_args.image_processor -# image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') -# if self.data_args.image_aspect_ratio == 'pad': -# def expand2square(pil_img, background_color): -# width, height = pil_img.size -# if width == height: -# return pil_img -# elif width > height: -# result = Image.new(pil_img.mode, (width, width), background_color) -# result.paste(pil_img, (0, (width - height) // 2)) -# return result -# else: -# result = Image.new(pil_img.mode, (height, height), background_color) -# result.paste(pil_img, ((height - width) // 2, 0)) -# return result -# image = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) -# image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] -# else: -# image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] -# sources = preprocess_multimodal( -# copy.deepcopy([e["conversations"] for e in sources]), -# self.data_args) -# else: -# sources = copy.deepcopy([e["conversations"] for e in sources]) -# data_dict = preprocess( -# sources, -# self.tokenizer, -# has_image=('image' in self.list_data_dict[i])) -# if isinstance(i, int): -# data_dict = dict(input_ids=data_dict["input_ids"][0], -# labels=data_dict["labels"][0]) - -# # image exist in the data -# if 'image' in self.list_data_dict[i]: -# data_dict['image'] = image -# elif self.data_args.is_multimodal: -# # image does not exist in the data, but the model is multimodal -# crop_size = self.data_args.image_processor.crop_size -# data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) -# return data_dict - - def next_rand(self): - import random - return random.randint(0,len(self)-1) - - def __getitem__(self, i) -> Dict[str, torch.Tensor]: - while True: - sources = self.list_data_dict[i] - if isinstance(i, int): - sources = [sources] - assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME - if 'image' in sources[0]: - image_file = self.list_data_dict[i]['image'] - - image_folder = self.data_args.image_folder - processor = self.data_args.image_processor - from pathlib import Path - #if not Path(os.path.join(image_folder, image_file)).exists(): - # i = self.next_rand() - # continue - if isinstance(image_file, list): - # Multiple Images as Input - try: - image = [Image.open(os.path.join(image_folder, imfile)).convert('RGB') for imfile in image_file] - except Exception as ex: - print(ex) - i = self.next_rand() - continue - if self.data_args.image_aspect_ratio == 'pad': - image = [expand2square(img, tuple(int(x*255) for x in processor.image_mean)) for img in image] - image = processor.preprocess(image, return_tensors='pt')['pixel_values'] - else: - image = processor.preprocess(image, return_tensors='pt')['pixel_values'] - elif os.path.join(image_folder, image_file).endswith("mp4"): - # Video as Input - image = load_video(os.path.join(image_folder, image_file)) - if self.data_args.image_aspect_ratio == 'pad': - image = [expand2square(img, tuple(int(x*255) for x in processor.image_mean)) for img in image] - image = processor.preprocess(image, return_tensors='pt')['pixel_values'] - else: - image = processor.preprocess(image, return_tensors='pt')['pixel_values'] - else: - try: - image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') - except Exception as ex: - print(ex) - i = self.next_rand() - continue - if self.data_args.image_aspect_ratio == 'pad': - image = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) - image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] - else: - image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] - sources = preprocess_multimodal( - copy.deepcopy([e["conversations"] for e in sources]), - self.data_args) - else: - - sources = copy.deepcopy([e["conversations"] for e in sources]) - data_dict = preprocess( - sources, - self.tokenizer, - has_image=('image' in self.list_data_dict[i])) - if isinstance(i, int): - data_dict = dict(input_ids=data_dict["input_ids"][0], - labels=data_dict["labels"][0]) - - # image exist in the data - if 'image' in self.list_data_dict[i]: - data_dict['image'] = image - elif self.data_args.is_multimodal: - # image does not exist in the data, but the model is multimodal - crop_size = self.data_args.image_processor.crop_size - data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) - return data_dict - - -@dataclass -class DataCollatorForSupervisedDataset(object): - """Collate examples for supervised fine-tuning.""" - - tokenizer: transformers.PreTrainedTokenizer - - def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: - input_ids, labels = tuple([instance[key] for instance in instances] - for key in ("input_ids", "labels")) - input_ids = torch.nn.utils.rnn.pad_sequence( - input_ids, - batch_first=True, - padding_value=self.tokenizer.pad_token_id) - labels = torch.nn.utils.rnn.pad_sequence(labels, - batch_first=True, - padding_value=IGNORE_INDEX) - input_ids = input_ids[:, :self.tokenizer.model_max_length] - labels = labels[:, :self.tokenizer.model_max_length] - batch = dict( - input_ids=input_ids, - labels=labels, - attention_mask=input_ids.ne(self.tokenizer.pad_token_id), - ) - - if 'image' in instances[0]: - images = [instance['image'] for instance in instances] - if all(x is not None and x.shape == images[0].shape for x in images): - batch['images'] = torch.stack(images) - else: - batch['images'] = images - - return batch - - -def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, - data_args) -> Dict: - """Make dataset and collator for supervised fine-tuning.""" - train_dataset = LazySupervisedDataset(tokenizer=tokenizer, - data_path=data_args.data_path, - data_args=data_args) - data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) - return dict(train_dataset=train_dataset, - eval_dataset=None, - data_collator=data_collator) - - -def train(): - global local_rank - - parser = transformers.HfArgumentParser( - (ModelArguments, DataArguments, TrainingArguments)) - model_args, data_args, training_args = parser.parse_args_into_dataclasses() - local_rank = training_args.local_rank - compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) - - bnb_model_from_pretrained_args = {} - if training_args.bits in [4, 8]: - from transformers import BitsAndBytesConfig - bnb_model_from_pretrained_args.update(dict( - device_map={"": training_args.device}, - load_in_4bit=training_args.bits == 4, - load_in_8bit=training_args.bits == 8, - quantization_config=BitsAndBytesConfig( - load_in_4bit=training_args.bits == 4, - load_in_8bit=training_args.bits == 8, - llm_int8_threshold=6.0, - llm_int8_has_fp16_weight=False, - bnb_4bit_compute_dtype=compute_dtype, - bnb_4bit_use_double_quant=training_args.double_quant, - bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} - ) - )) - - model = MPLUGOwl2LlamaForCausalLM.from_pretrained( - model_args.model_name_or_path, - cache_dir=training_args.cache_dir, - **bnb_model_from_pretrained_args - ) - model.config.use_cache = False - - if model_args.freeze_backbone: - model.model.requires_grad_(False) - - if training_args.bits in [4, 8]: - from peft import prepare_model_for_kbit_training - model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) - model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) - - if training_args.gradient_checkpointing: - if hasattr(model, "enable_input_require_grads"): - model.enable_input_require_grads() - else: - def make_inputs_require_grad(module, input, output): - output.requires_grad_(True) - model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) - - if training_args.lora_enable: - from peft import LoraConfig, get_peft_model - lora_config = LoraConfig( - r=training_args.lora_r, - lora_alpha=training_args.lora_alpha, - target_modules=find_all_linear_names(model), - lora_dropout=training_args.lora_dropout, - bias=training_args.lora_bias, - task_type="CAUSAL_LM", - ) - if training_args.bits == 16: - if training_args.bf16: - model.to(torch.bfloat16) - if training_args.fp16: - model.to(torch.float16) - rank0_print("Adding LoRA adapters...") - model = get_peft_model(model, lora_config) - - tokenizer = transformers.AutoTokenizer.from_pretrained( - model_args.model_name_or_path, - cache_dir=training_args.cache_dir, - model_max_length=training_args.model_max_length, - padding_side="right", - use_fast=False, - ) - - - tokenizer.pad_token = tokenizer.unk_token - if model_args.version in conversation_lib.conv_templates: - conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] - else: - conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] - - if not training_args.freeze_vision_model and training_args.bits in [4, 8]: - model.get_model().vision_model.to(dtype=compute_dtype, device=training_args.device) - else: - vision_tower = model.get_model().vision_model - vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) - - if training_args.tune_visual_abstractor and training_args.bits in [4, 8]: - model.get_model().visual_abstractor.to(dtype=compute_dtype, device=training_args.device) - else: - visual_abstractor = model.get_model().visual_abstractor - visual_abstractor.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) - - data_args.image_processor = CLIPImageProcessor.from_pretrained(model_args.model_name_or_path) - data_args.is_multimodal = True - - model.config.image_aspect_ratio = data_args.image_aspect_ratio - model.config.image_grid_pinpoints = data_args.image_grid_pinpoints - model.config.tune_visual_abstractor = model_args.tune_visual_abstractor = training_args.tune_visual_abstractor - ic(training_args.tune_visual_abstractor) - model.requires_grad_(True) - if training_args.tune_visual_abstractor: - # model.requires_grad_(False) - for p in model.get_model().visual_abstractor.parameters(): - p.requires_grad = True - - model.config.freeze_vision_model = training_args.freeze_vision_model - ic(training_args.freeze_vision_model) - if training_args.freeze_vision_model: - for p in model.get_model().vision_model.parameters(): - p.requires_grad = False - - model.config.visual_abstractor_lr = training_args.visual_abstractor_lr - - - if training_args.bits in [4, 8]: - from peft.tuners.lora import LoraLayer - for name, module in model.named_modules(): - if isinstance(module, LoraLayer): - if training_args.bf16: - module = module.to(torch.bfloat16) - if 'norm' in name: - module = module.to(torch.float32) - if 'lm_head' in name or 'embed_tokens' in name: - if hasattr(module, 'weight'): - if training_args.bf16 and module.weight.dtype == torch.float32: - module = module.to(torch.bfloat16) - - data_module = make_supervised_data_module(tokenizer=tokenizer, - data_args=data_args) - trainer = MPLUGOwl2Trainer(model=model, - tokenizer=tokenizer, - args=training_args, - **data_module) - - # if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): - # trainer.train(resume_from_checkpoint=True) - # else: - # trainer.train() - - # TODO I dont like auto resume << REMOVE IT AND UNCOMMENT THE ABOVE CODE - trainer.train() - - trainer.save_state() - - model.config.use_cache = True - - if training_args.lora_enable: - state_dict = get_peft_state_maybe_zero_3( - model.named_parameters(), training_args.lora_bias - ) - non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( - model.named_parameters() - ) - if training_args.local_rank == 0 or training_args.local_rank == -1: - model.config.save_pretrained(training_args.output_dir) - model.save_pretrained(training_args.output_dir, state_dict=state_dict) - torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) - else: - safe_save_model_for_hf_trainer(trainer=trainer, - output_dir=training_args.output_dir) - - -if __name__ == "__main__": - train() \ No newline at end of file diff --git a/q_align/train/train_mem.py b/q_align/train/train_mem.py deleted file mode 100644 index 4698657df8e14de319a0c117948eb8fd8a4c67b3..0000000000000000000000000000000000000000 --- a/q_align/train/train_mem.py +++ /dev/null @@ -1,13 +0,0 @@ -# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: -# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: -# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn. - -# Need to call this before importing transformers. -from q_align.train.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn - -replace_llama_attn_with_flash_attn() - -from q_align.train.train import train - -if __name__ == "__main__": - train() \ No newline at end of file diff --git a/q_align/utils.py b/q_align/utils.py deleted file mode 100644 index 378dbc81cce765dea2cd138ae50f242fc557c2c9..0000000000000000000000000000000000000000 --- a/q_align/utils.py +++ /dev/null @@ -1,128 +0,0 @@ -import datetime -import logging -import logging.handlers -import os -import sys - -import requests - - - -from q_align.constants import LOGDIR - -server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" -moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN." - -handler = None - - -def build_logger(logger_name, logger_filename): - global handler - - formatter = logging.Formatter( - fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) - - # Set the format of root handlers - if not logging.getLogger().handlers: - logging.basicConfig(level=logging.INFO) - logging.getLogger().handlers[0].setFormatter(formatter) - - # Redirect stdout and stderr to loggers - stdout_logger = logging.getLogger("stdout") - stdout_logger.setLevel(logging.INFO) - sl = StreamToLogger(stdout_logger, logging.INFO) - sys.stdout = sl - - stderr_logger = logging.getLogger("stderr") - stderr_logger.setLevel(logging.ERROR) - sl = StreamToLogger(stderr_logger, logging.ERROR) - sys.stderr = sl - - # Get logger - logger = logging.getLogger(logger_name) - logger.setLevel(logging.INFO) - - # Add a file handler for all loggers - if handler is None: - os.makedirs(LOGDIR, exist_ok=True) - filename = os.path.join(LOGDIR, logger_filename) - handler = logging.handlers.TimedRotatingFileHandler( - filename, when='D', utc=True) - handler.setFormatter(formatter) - - for name, item in logging.root.manager.loggerDict.items(): - if isinstance(item, logging.Logger): - item.addHandler(handler) - - return logger - - -class StreamToLogger(object): - """ - Fake file-like stream object that redirects writes to a logger instance. - """ - def __init__(self, logger, log_level=logging.INFO): - self.terminal = sys.stdout - self.logger = logger - self.log_level = log_level - self.linebuf = '' - - def __getattr__(self, attr): - return getattr(self.terminal, attr) - - def write(self, buf): - temp_linebuf = self.linebuf + buf - self.linebuf = '' - for line in temp_linebuf.splitlines(True): - # From the io.TextIOWrapper docs: - # On output, if newline is None, any '\n' characters written - # are translated to the system default line separator. - # By default sys.stdout.write() expects '\n' newlines and then - # translates them so this is still cross platform. - if line[-1] == '\n': - self.logger.log(self.log_level, line.rstrip()) - else: - self.linebuf += line - - def flush(self): - if self.linebuf != '': - self.logger.log(self.log_level, self.linebuf.rstrip()) - self.linebuf = '' - - -def disable_torch_init(): - """ - Disable the redundant torch default initialization to accelerate model creation. - """ - import torch - setattr(torch.nn.Linear, "reset_parameters", lambda self: None) - setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) - - -def violates_moderation(text): - """ - Check whether the text violates OpenAI moderation API. - """ - url = "https://api.openai.com/v1/moderations" - headers = {"Content-Type": "application/json", - "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} - text = text.replace("\n", "") - data = "{" + '"input": ' + f'"{text}"' + "}" - data = data.encode("utf-8") - try: - ret = requests.post(url, headers=headers, data=data, timeout=5) - flagged = ret.json()["results"][0]["flagged"] - except requests.exceptions.RequestException as e: - flagged = False - except KeyError as e: - flagged = False - - return flagged - - -def pretty_print_semaphore(semaphore): - if semaphore is None: - return "None" - return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" \ No newline at end of file diff --git a/requirements-zerogpu.txt b/requirements-zerogpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9f951c10d314efc0f55eadce361aef2d5bcf423 --- /dev/null +++ b/requirements-zerogpu.txt @@ -0,0 +1,12 @@ +gradio==6.30.0 +spaces==0.51.3 +torch==2.13.0 +torchvision==0.28.0 +transformers==5.14.1 +peft==0.20.0 +accelerate==1.14.0 +safetensors==0.8.0 +pillow==12.3.0 +pydantic==2.13.4 +httpx==0.28.1 +nodejs-wheel-binaries==24.19.0 diff --git a/requirements.txt b/requirements.txt index 2afcaa09b11343ab7e44435fbdbc8f04b4c357bf..b5a1bef1897a7c7bebfe5d59f3d0728e79dcc7f5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,20 +1,3 @@ -icecream -markdown2 -pydantic -accelerate==0.21.0 -transformers==4.31.0 -tokenizers==0.12.1 -sentencepiece==0.1.99 -shortuuid -bitsandbytes==0.41.0 -timm==0.6.13 -requests -httpx==0.24.0 -uvicorn -einops-exts==0.0.4 -einops==0.6.1 -scikit-learn==1.2.2 -numpy -gradio==4.12.0 -gradio_client==0.8.0 -decord \ No newline at end of file +gradio==6.30.0 +httpx==0.28.1 +nodejs-wheel-binaries==24.19.0 diff --git a/upstream/CITATION.cff b/upstream/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..af26da905877a9cdce26a6153a71756332190437 --- /dev/null +++ b/upstream/CITATION.cff @@ -0,0 +1,17 @@ +cff-version: 1.2.0 +title: "imajev: an open Jev-style decision model for images and text" +message: "If you use imajev, please cite it as below." +type: software +authors: + - family-names: Garg + given-names: Mohit + alias: mohit67890 +version: 1.1.0 +date-released: 2026-09-26 +license: Apache-2.0 +repository-code: https://github.com/mohit67890/imajev +keywords: + - typed decisions + - vision-language + - calibration + - Jev diff --git a/upstream/LICENSE b/upstream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..11cebea23afc712a6420c222c92d903224c1c044 --- /dev/null +++ b/upstream/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Mohit Garg + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/upstream/scripts/playground/examples.py b/upstream/scripts/playground/examples.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0e95316c2d1a4961e4eeea7a1f6497f5174872 --- /dev/null +++ b/upstream/scripts/playground/examples.py @@ -0,0 +1,292 @@ +"""Example requests for the playground's "Load example" menu (docs/playground-spec.md). + +Each example carries repository-relative image paths so the server can load the images itself; +`GET /examples/{n}/image/{i}` serves them to the UI. `load_examples()` drops any example whose +images are missing from the checkout rather than advertising a broken menu entry. + +Every question here was checked against the v1 adapter (see "verified" notes): the menu is meant to +show the model's real behaviour, so an example either gets the answer right or exists to show an +abstention. Two things the v1 model is known to be shaky on are deliberately avoided: score scales +for subjective photo quality with fewer than 4 levels (it puts ~all mass on unknown, because the +training data only ever used a 5-point scale), and asking which state field a *second* image +contradicts (it answers that correctly from one image and flips with two). +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + +STATE_AWARE = "data/decision-v1/state_aware/images" +TALLYQA = "data/decision-v1/tallyqa/images" +ABSTAIN = "data/decision-v1/heldout_abstention/images" +TEXTVQA = "data/decision-v1/textvqa/images" + +CUTLERY = f"{STATE_AWARE}/21e6886fae2b31f208de0150a03c9d46af5fed5e6904d50e03f8107c99880278.jpg" +OXFORD = f"{STATE_AWARE}/a0e8fbdd569a7f7c0cec0aafb0c6bf63df05f50ba02a9814261f7d7bf07783cd.jpg" +SNEAKER = f"{STATE_AWARE}/1b3ac44bf8066c9894fefcf53af026a030e61b04280cf2f3386dcbde601f0a87.jpg" + +# Photo-quality scores need a 5-level scale; on 3 levels the model abstains with unknown ≈ 0.99. +USABILITY = ["unusable: blurry, dark or badly cropped", "poor", "acceptable", "good", + "excellent: sharp, well lit, product fills the frame"] + +EXAMPLES = [ + { + "name": "Product listing check", + "description": "One product photo against a marketplace listing that is correct: colour match, category, photo usability. Verified: true 0.99, cutlery 0.97, usability 2.5 of 4.", + "images": [CUTLERY], + "request": { + "state": {"listing": {"title": "24 Piece Stainless Steel Cutlery Set, Stripes (Contains: 6 Table Spoons, 6 Tea Spoons, 6 Forks, 6 Soup Spoons)", "color": "silver", "product_type": "cutlery"}}, + "questions": { + "color_matches": { + "type": "noul", + "instructions": "The product in the photo matches `listing.color`.", + "criteria": {"true": "the dominant colour of the product is the listed colour", + "false": "the product is clearly a different colour from the listed one"}, + }, + "product_type": { + "type": "choice", + "instructions": "Which category does the photographed item belong to?", + "criteria": {"cutlery": "knives, forks, spoons", "cookware": "pots and pans", "tableware": "plates, bowls, glasses", "other": None}, + }, + "photo_usability": { + "type": "score", + "instructions": "How usable is this photo as the main listing image?", + "criteria": USABILITY, + }, + }, + }, + }, + { + "name": "Listing field contradiction", + "description": "The same check on a listing that is wrong: the shoe in the photo is black, the listing says brown. Verified: false 0.02, and the choice picks `listing.color` at 0.98.", + "images": [SNEAKER], + "request": { + "state": {"listing": {"title": "Men's Lace-Up Shoes", "color": "brown", "product_type": "shoe"}}, + "questions": { + "color_matches": { + "type": "noul", + "instructions": "The product in the photo matches `listing.color`.", + "criteria": {"true": "the product is the listed colour", + "false": "the product is clearly a different colour from the listed one"}, + }, + "contradicted_field": { + "type": "choice", + "instructions": "Which listed field does this photo contradict?", + "criteria": {"listing.color": "the photo shows a different colour than `listing.color`", + "listing.product_type": "the photo shows a different kind of product than `listing.product_type`", + "none of them": "the photo is consistent with the listing"}, + }, + }, + }, + }, + { + "name": "Two-image same-product", + "description": "Reference listing photo vs a second photo of a different shoe: both questions reason across the two images. Verified: same_item 0.00, the first photo 0.66, black 0.60 — note how much lower the confidence is than on one image.", + "images": [OXFORD, SNEAKER], + "request": { + "state": {"listing": {"title": "Men's Formal Oxford Shoes", "color": "brown", "product_type": "shoe"}}, + "questions": { + "same_item": { + "type": "noul", + "instructions": "The second photo shows the item described in `listing`.", + "criteria": {"true": "the second photo shows the same product as the listing and the reference photo", + "false": "the second photo shows a different product"}, + }, + "matching_photo": { + "type": "choice", + "instructions": "Which photo shows the product described in `listing`?", + "criteria": {"the first photo": None, "the second photo": None, + "both photos": None, "neither photo": None}, + }, + "second_color": { + "type": "choice", + "instructions": "What is the dominant colour of the product in the second photo?", + "criteria": {"brown": None, "black": None, "white": None, "other": None}, + }, + }, + }, + }, + { + "name": "Counting as score", + "description": "An ordinal question used as a counter: the score type gives a distribution over 0-6 people. Verified: 3.01, with 0.78 on 'three people'.", + "images": [f"{TALLYQA}/dcdc070d27438efb56ae31076174113440103634877d074c9ac5083a5df70bd6.jpg"], + "request": { + "state": {}, + "questions": { + "people": { + "type": "score", + "instructions": "How many people are visible in the photo?", + "criteria": ["no people", "one person", "two people", "three people", + "four people", "five people", "six or more people"], + }, + }, + }, + }, + { + "name": "Abstention showcase", + "description": "Two questions should abstain: there is no dog (false premise) and the shirt colour the model reads, green, is not among the options (not listed). Bag colour and mood are answerable controls. Add an 'other' option to shirt_color to see the model pick it (0.98) instead of abstaining.", + "images": [f"{ABSTAIN}/dc020c1f7b783a0fbd6d518b0e5e021a5a735312bd9a3b14b940ce8ca02adeb0.jpg"], + "request": { + "state": {}, + "questions": { + "dog_color": { + "type": "choice", + "instructions": "What colour is the dog standing next to him?", + "criteria": {"red": None, "blue": None, "black": None, "white": None}, + }, + "shirt_color": { + "type": "choice", + "instructions": "What colour is his shirt?", + "criteria": {"red": None, "blue": None, "black": None}, + }, + "bag_color": { + "type": "choice", + "instructions": "What colour is the bag?", + "criteria": {"purple": None, "green": None, "gray": None, "black": None}, + }, + "mood": { + "type": "choice", + "instructions": "Which mood does the figure convey?", + "criteria": {"sad": None, "angry": None, "happy": None}, + }, + }, + }, + }, + { + "name": "Document / scene text", + "description": "A held-out TextVQA photo: a choice over candidate OCR tokens plus a legibility score. Verified: palm 1.00, legibility 3.3 of 4.", + # TextVQA's val split, so the answer is read off the photo rather than remembered from training. + "images": [f"{TEXTVQA}/1739daa601540017c980dce24fadae37fe9f2368790df2ae232854c0d39f2ac3.jpg"], + "request": { + "state": {"task": "read the branding on the device"}, + "questions": { + "brand": { + "type": "choice", + "instructions": "Which brand name is printed on the device?", + "criteria": {"palm": None, "sony": None, "nokia": None, "tokyo bullet": None}, + }, + "text_legible": { + "type": "score", + "instructions": "How legible is the branding in this photo?", + "criteria": ["illegible", "mostly illegible", "partly legible", "mostly legible", "fully legible"], + }, + }, + }, + }, + { + "name": "Text-only: support ticket triage", + "description": "No image at all: a support email as state, routed and triaged in one pass. The model runs the same prompt and decision position as an image request, with the vision tower skipped. Verified: billing 0.89, urgent 0.98, frustration 1.5 of 2.", + "images": [], + "request": { + "state": { + "ticket": { + "id": "TKT-48812", + "from": "dana.okafor@northwind-labs.example", + "received": "2026-09-21T08:14:00Z", + "subject": "Charged twice for the September seats - third email", + "body": ("We were billed 480 USD twice on 3 September for the same 12 seats. " + "I have now written three times and the only reply was an automated one. " + "Our finance close is on Wednesday and I need the duplicate reversed before then. " + "Nothing is broken in the product itself."), + "plan": "Team (12 seats)", + "prior_tickets_90d": 2, + }, + }, + "questions": { + "department": { + "type": "choice", + "instructions": "Which department should own this ticket?", + "criteria": { + "billing": "payments, invoices, refunds and subscription charges", + "technical_support": "the product is broken, erroring or unavailable", + "sales": "new seats, upgrades, quotes and renewals", + "account_management": "ownership, access and contract administration", + }, + }, + "urgent": { + "type": "noul", + "instructions": "This ticket needs a reply today.", + "criteria": {"true": "money is at stake or the customer has a dated deadline within days", + "false": "it can wait for the normal queue"}, + }, + "frustration": { + "type": "score", + "instructions": "How frustrated does the customer sound?", + "criteria": ["calm and matter-of-fact", + "impatient: chasing a reply or repeating themselves", + "angry: threatening to escalate, churn or dispute the charge"], + }, + }, + }, + }, + { + "name": "Text-only: resume screening", + "description": "State as a plain string rather than JSON, and object-form instructions ({\"question\": ..., \"today\": ...}) so the model can do date arithmetic. Six-option choice, a 6-level score and a noul. Verified: experience 3.5 of 5 (the candidate is at about 7 years, so this is one level low), mentorship 0.93, and it picks engineering_management at 0.49 over backend_systems — a good example of a low-confidence choice you would gate rather than act on.", + "images": [], + "request": { + "state": ("Priya Raghunathan - Bengaluru, India. " + "2022-03 to now: Senior Backend Engineer, Zeltic Payments - owns the ledger service " + "(Go, Postgres, Kafka), led the migration off a monolith, runs the on-call rotation for six engineers " + "and writes the internal design-review guide. " + "2019-07 to 2022-02: Backend Engineer, Turnstile Health - billing APIs in Python. " + "2018-06 to 2019-06: intern, then junior developer, Kaveri Systems. " + "B.E. Computer Science, PES University, 2018. " + "Speaks at the Bengaluru Go meetup; mentored four interns to full-time offers."), + "questions": { + "experience_years": { + "type": "score", + "instructions": { + "question": "How many years of professional software engineering experience does this candidate have?", + "today": "September 22, 2026", + "note": "Count paid full-time work only; internships do not count.", + }, + "criteria": ["less than 1 year", "1 to 2 years", "3 to 4 years", + "5 to 6 years", "7 to 9 years", "10 years or more"], + }, + "would_mentor": { + "type": "noul", + "instructions": "This candidate would be effective mentoring junior engineers.", + "criteria": {"true": "there is evidence of teaching, reviewing or growing other engineers", + "false": "the record is individual-contributor work only"}, + }, + "talent_profile": { + "type": "choice", + "instructions": "Which profile fits this candidate best?", + "criteria": { + "backend_systems": "services, data stores and distributed systems", + "frontend_product": "user interfaces and client applications", + "data_ml": "data pipelines, analytics or machine learning", + "infrastructure_sre": "platform, deployment and reliability engineering", + "security": "application or infrastructure security", + "engineering_management": "primarily leads people rather than writes code", + }, + }, + }, + }, + }, +] + + +def load_examples(root=ROOT): + """Examples whose images all exist under `root`, each with UI-ready image descriptors. + + An example with an empty `images` list is a text-only example and is always listed. + """ + root = Path(root) + out = [] + for example in EXAMPLES: + paths = [root / name for name in example["images"]] + if not all(path.is_file() for path in paths): + continue + index = len(out) + out.append({ + "index": index, + "name": example["name"], + "description": example["description"], + "request": example["request"], + "images": [{"index": i, "path": name, "name": Path(name).name, + "role": "reference" if i == 0 else "target", + "bytes": path.stat().st_size, + "url": f"/examples/{index}/image/{i}?v={Path(path).stem[:12]}"} # cache-buster: image files are content-addressed + for i, (name, path) in enumerate(zip(example["images"], paths))], + }) + return out diff --git a/upstream/scripts/playground/server.py b/upstream/scripts/playground/server.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ea90248404e50cad3f2f9a293338841b401570 --- /dev/null +++ b/upstream/scripts/playground/server.py @@ -0,0 +1,539 @@ +"""Local playground HTTP API for the imajev decision model — see docs/playground-spec.md ("HTTP API"). + +Run it directly: + .venv/bin/python scripts/playground/server.py --backend auto +The model loads once at startup and stays resident; a lock keeps requests strictly sequential +because there is only one GPU. +""" +from __future__ import annotations + +import argparse +import base64 +import binascii +import json +import logging +import mimetypes +import re +import sys +import threading +from datetime import datetime, timezone +from pathlib import Path +from time import perf_counter + +ROOT = Path(__file__).resolve().parents[2] +for extra in (ROOT / "src", ROOT / "scripts", Path(__file__).resolve().parent): + if str(extra) not in sys.path: + sys.path.insert(0, str(extra)) + +from fastapi import FastAPI, HTTPException # noqa: E402 +from fastapi.exceptions import RequestValidationError # noqa: E402 +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse # noqa: E402 +from fastapi.staticfiles import StaticFiles # noqa: E402 +from pydantic import ValidationError # noqa: E402 +from starlette.concurrency import run_in_threadpool # noqa: E402 +from starlette.requests import Request as HttpRequest # noqa: E402 + +from vision_decision.images import MAX_BYTES, load_image_bytes # noqa: E402 +from vision_decision.jev_api import MAX_OPTIONS, to_request_with_plan, to_response # noqa: E402 +from vision_decision.thinking import ThinkingPolicy # noqa: E402 +from vision_decision.scoring import (check_prompt_layout, check_readout_codes, combine_rotations, compile_question, # noqa: E402 + cyclic_offsets, result_from_logits, rotate) + +try: # package import (PYTHONPATH=scripts) or plain script run + from .examples import load_examples +except ImportError: # pragma: no cover - exercised only when run as a script + from examples import load_examples + +# Public model names. The base checkpoint behind the adapter is an implementation detail and is +# deliberately not part of the API or the UI; `/v1/models` still reports the adapter directory. +MODEL_NAME = "imajev-v1.1" +BASE_MODEL_NAME = "imajev-v1.1-base" + +MLX_ADAPTER = ROOT / "reports/decision-v1/runs/h100x4-full/best-mlx" +TORCH_ADAPTER = ROOT / "reports/decision-v1/runs/h100x4-full/best" +BUNDLE = ROOT / "artifacts/model.json" +STATIC = Path(__file__).resolve().parent / "static" +DATA_URL = re.compile(r"^data:(?P[\w.+-]+/[\w.+-]+)?(?P;base64)?,(?P.*)$", re.DOTALL) + +log = logging.getLogger("playground") + + +class PlaygroundError(Exception): + """A request the server refuses; `status` is the HTTP code and `detail` the human message.""" + + def __init__(self, status, error, detail): + super().__init__(detail) + self.status, self.error, self.detail = status, error, detail + + +def _image_status(message): + """20 MiB / 20 Mpixel limits are 413; everything else about an image is a 422.""" + return 413 if "exceeds 20 MiB" in message or "20 million decoded pixels" in message else 422 + + +# --------------------------------------------------------------------------------------- backends + +class MLXBackend: + """MLX path: one image prefill shared by every question of the request.""" + + name = "mlx" + + def __init__(self, bundle=BUNDLE, adapter=None, rotations=1, max_input_tokens=4096, readout_codes=None, prompt_layout=None): + from vision_decision.backend import MLXDirect + self.engine = MLXDirect(str(bundle), adapter=None if adapter is None else str(adapter), + max_input_tokens=max_input_tokens, readout_codes=readout_codes, prompt_layout=prompt_layout) + self.readout_codes, self.prompt_layout = self.engine.codes, self.engine.prompt_layout + self.max_options = self.engine.max_options + _warn_layout(self.engine.trained_prompt_layout, self.prompt_layout) + self.adapter = None if adapter is None else str(adapter) + self.model = MODEL_NAME if adapter else BASE_MODEL_NAME + self.load_seconds = self.engine.load_seconds + self.rotations = rotations + + def score(self, images, request): + # One image is passed on its own, a pair as a list; [] is a text-only request. + target = images[0] if len(images) == 1 else list(images) + results, run = self.engine.score_request(target, request.fields, request.state, self.rotations) + passes = [row for detail in run.get("questions", []) for row in detail["rotations"]] + return results, { + "prefill_ms": round(run.get("prefill_seconds", 0.0) * 1000, 1), + "questions_ms": round(sum(row["forward_seconds"] for row in passes) * 1000, 1), + "input_tokens": max((row["input_tokens"] for row in passes), default=0), + } + + +class TorchBackend: + """PyTorch fallback: one full forward per question, never a batch (left padding NaNs on MPS).""" + + name = "torch" + supports_thinking = True + + def __init__(self, bundle=BUNDLE, adapter=None, device=None, rotations=1, max_input_tokens=4096, readout_codes=None, + prompt_layout=None, fast=False, graph_lengths=None, merge_lora=False, float32=False): + import torch + from torch_decision import GRAPH_LENGTHS, TorchDecision + self.torch = torch + self.rotations = max(1, int(rotations)) + self.fast = bool(fast) + if device is None: # CUDA on a pod or Space, Metal on a Mac, CPU otherwise + device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" + self.bundle = json.loads(Path(bundle).read_text()) + if not Path(self.bundle["path"]).is_dir(): + raise ValueError("Local model snapshot is missing; run scripts/download_model.py") + start = perf_counter() + dtype = torch.bfloat16 if device == "cuda" and not float32 else torch.float32 + # --merge-lora loads in float32 so the merge is formed at full precision, then rounds once to the serving dtype. + # In bf16 that rounding still moves near-tie decisions (and calibration), so it is opt-in; --fast alone keeps + # the LoRA unmerged and computes exactly the benchmarked function. + merge = bool(merge_lora) and adapter is not None + # The float32 merge runs on the CPU (no float32 copy on the GPU); the rounded weights then move to the device. + self.engine = TorchDecision(self.bundle["path"], "cpu" if merge else device, dtype=torch.float32 if merge else dtype, + max_length=int(max_input_tokens)) + if adapter is not None: + if merge: + self.engine.merge_adapter(adapter, dtype) + self.engine.model.to(device); self.engine.device = device + else: + from peft import PeftModel + self.engine.model = PeftModel.from_pretrained(self.engine.model, str(adapter)).eval() + self.engine.enable_readout(adapter, trainable=False, codes=readout_codes) + self.graph_lengths = [] + if self.fast and device == "cuda": + lengths = [n for n in (graph_lengths or GRAPH_LENGTHS) if n <= int(max_input_tokens)] + try: + self.graph_lengths = self.engine.capture_graphs(lengths).lengths + except Exception: # the eager path computes the same function + log.exception("CUDA graph capture failed; serving the eager path") + self.engine.graphs = None + if self.engine.readout is None and readout_codes is not None: # base model / legacy adapter: LM-head rows + self.engine.codes = check_readout_codes(readout_codes) + trained = self.engine.prompt_layout # the adapter's recorded layout (standard when absent) + self.prompt_layout = trained if prompt_layout is None else check_prompt_layout(prompt_layout) + _warn_layout(trained, self.prompt_layout) + self.readout_codes, self.max_options = self.engine.codes, self.engine.max_options + self.adapter = None if adapter is None else str(adapter) + self.model = MODEL_NAME if adapter else BASE_MODEL_NAME + self.load_seconds = perf_counter() - start + + def score(self, images, request, thinking=None): + """One forward per question and per presentation order; with rotations > 1 the per-candidate log-probabilities + are averaged over cyclic option orders exactly as the MLX path does (combine_rotations), which drops the engine's + vocabulary tie break; with rotations == 1 the single pass keeps it. + + thinking (a ThinkingPolicy, None = off): a question whose single-pass answer the policy calls unsure gets a greedy + thought of at most max_tokens, and its decision is read again right after the thought (docs/think-if-unsure-plan.md).""" + if thinking is not None and thinking.active and self.rotations != 1: + raise PlaygroundError(422, "invalid_request", "thinking needs a server running --rotations 1") + results, seconds, tokens, thoughts = [], 0.0, 0, [] + for field in request.fields: + header, choices, texts = compile_question(field, request.state, getattr(self, "prompt_layout", "standard")) + labels = self.engine.labels(len(choices), len(images)) + start = perf_counter() + passes = [] + for offset in cyclic_offsets(len(choices), self.rotations): + prompt = header + "\n".join(f"{label}: {text}" for label, text in zip(labels, rotate(texts, offset))) + if getattr(self, "fast", False): + with self.torch.inference_mode(): + _, inputs, token_ids = self.engine.prepare_fast(images, prompt, labels) + logits = [float(x) for x in self.engine.candidate_logits_fast(inputs, token_ids).cpu().tolist()] + else: + with self.torch.no_grad(): + _, inputs, token_ids = self.engine.prepare(images, prompt, labels) + logits = [float(x) for x in self.engine.candidate_logits(inputs, token_ids).cpu().tolist()] + tokens = max(tokens, int(inputs["input_ids"].shape[-1])) + passes.append((offset, logits, token_ids)) + seconds += perf_counter() - start + if len(passes) == 1: + result = result_from_logits(choices, passes[0][1], token_ids=passes[0][2]) + else: + result = combine_rotations(choices, [(offset, logits) for offset, logits, _ in passes]) + if thinking is not None and thinking.should_think(result): + start = perf_counter() + thought_result, note = self._think(images, prompt, choices, labels, thinking) + result = thought_result or result + note["think_ms"] = round((perf_counter() - start) * 1000, 1) + thoughts.append({"question": field.id, **note}) + results.append(result) + # No shared prefill on this path: the whole cost is reported per question. + usage = {"prefill_ms": 0.0, "questions_ms": round(seconds * 1000, 1), "input_tokens": tokens, "rotations": self.rotations} + if thinking is not None and thinking.active: + usage["thinking"] = {"mode": thinking.mode, "max_tokens": thinking.max_tokens, "thought": thoughts} + return results, usage + + def _think(self, images, prompt, choices, labels, thinking): + """-> (the Result read after a greedy thought, a usage note). `prompt` is the rotations == 1 single-pass prompt.""" + engine = getattr(self, "thoughts", None) # a VLLMThoughts client (--think-engine vllm), else transformers generate + try: + tokens, closed = engine.think(images, prompt, thinking.max_tokens)[:2] if engine else self.engine.generate_thought(images, prompt, thinking.max_tokens) + except Exception as exc: # no thought (e.g. a prompt longer than the thought engine's context): keep the single pass + log.warning("thought failed, keeping the single-pass answer: %s", exc) + return None, {"thought_tokens": 0, "closed": False, "error": f"{type(exc).__name__}: {str(exc)[:200]}"} + inputs, token_ids = self.engine.inputs_after_thought(images, prompt, labels, tokens, closed) + with self.torch.inference_mode(): + scored = self.engine.candidate_logits_fast(inputs, token_ids) if getattr(self, "fast", False) else self.engine.candidate_logits(inputs, token_ids) + logits = [float(x) for x in scored.cpu().tolist()] + note = {"thought_tokens": len(tokens), "closed": closed} + if thinking.return_thought: + note["text"] = self.engine.processor.tokenizer.decode(tokens) + return result_from_logits(choices, logits, token_ids=token_ids), note + + +def _warn_layout(trained, served): + if trained != served: + log.warning("serving prompt layout %r but the adapter was trained with %r", served, trained) + + +def build_backend(kind, adapter=None, no_adapter=False, bundle=BUNDLE, rotations=1, max_input_tokens=4096, + readout_codes=None, prompt_layout=None, fast=False, merge_lora=False, float32=False): + """`auto` prefers MLX with the converted adapter and falls back to torch + the PEFT adapter. + + readout_codes None / prompt_layout None follow the adapter (its readout rows; its decision_readout.json layout).""" + if kind == "auto": + kind = "mlx" if MLX_ADAPTER.is_dir() else "torch" + default = MLX_ADAPTER if kind == "mlx" else TORCH_ADAPTER + if no_adapter: + chosen = None + elif adapter is not None: + chosen = Path(adapter) + else: + chosen = default if default.is_dir() else None + if chosen is None: + log.warning("adapter %s is missing; serving the base model", default) + if chosen is not None and not Path(chosen).is_dir(): + raise ValueError(f"Adapter directory {chosen} does not exist") + if kind == "mlx": + return MLXBackend(bundle, chosen, rotations=rotations, max_input_tokens=max_input_tokens, + readout_codes=readout_codes, prompt_layout=prompt_layout) + if kind == "torch": + return TorchBackend(bundle, chosen, rotations=rotations, max_input_tokens=max_input_tokens, + readout_codes=readout_codes, prompt_layout=prompt_layout, fast=fast, merge_lora=merge_lora, + float32=float32) + raise ValueError(f"Unknown backend {kind!r}") + + +# ----------------------------------------------------------------------------------- request body + +def decode_data_url(value, position): + if not isinstance(value, str) or not value: + raise PlaygroundError(422, "bad_image", f"images[{position}] must be a data URL string") + match = DATA_URL.match(value.strip()) + if match is None: + raise PlaygroundError(422, "bad_image", f"images[{position}] is not a data: URL") + if not match.group("b64"): + raise PlaygroundError(422, "bad_image", f"images[{position}] must be base64-encoded (data:...;base64,...)") + try: + return base64.b64decode(match.group("payload"), validate=True) + except (binascii.Error, ValueError): + raise PlaygroundError(422, "bad_image", f"images[{position}] is not valid base64") + + +IMAGE_DATA_URL = re.compile(r"data:image/[\w.+-]+;base64,[A-Za-z0-9+/=]+") + + +def extract_state_images(payload): + """Image JevBench-style requests carry the photo as a data:image URI inside the state instead of the `images` field. + Pull every such URI out of the state (a string, a dict value, a list item or a messages[].content), in reading order, + replace it with "[image N]" and return the data URLs. The state keeps its structure; nothing else is touched.""" + found = [] + + def take(value): + if not isinstance(value, str) or "data:image/" not in value: + return value + def repl(match): + found.append(match.group(0)); return f"[image {len(found)}]" + return IMAGE_DATA_URL.sub(repl, value) + + def walk(node): + if isinstance(node, str): return take(node) + if isinstance(node, list): return [walk(x) for x in node] + if isinstance(node, dict): return {k: walk(v) for k, v in node.items()} + return node + + if "state" in payload and payload["state"] is not None: + payload["state"] = walk(payload["state"]) + return found + + +async def read_payload(http_request): + """-> (payload dict without images, [image bytes]) for multipart or JSON encodings.""" + content_type = (http_request.headers.get("content-type") or "").split(";")[0].strip().lower() + if content_type == "multipart/form-data": + try: + form = await http_request.form() + except Exception as exc: # malformed multipart body + raise PlaygroundError(422, "bad_request", f"Malformed multipart body: {exc}") + raw = form.get("request") + if raw is None: + raise PlaygroundError(422, "bad_request", "Missing the 'request' form field") + if not isinstance(raw, str): + raw = (await raw.read()).decode("utf-8", "replace") + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise PlaygroundError(422, "bad_json", f"The 'request' field is not valid JSON: {exc}") + blobs = [] + for key in ("image", "images", "image[]"): + for upload in form.getlist(key): + if isinstance(upload, str): + raise PlaygroundError(422, "bad_image", f"Form field {key!r} must be an uploaded file") + blobs.append(await upload.read()) + if isinstance(payload, dict): + blobs += [decode_data_url(value, i) for i, value in enumerate(extract_state_images(payload))] + elif content_type == "application/json": + body = await http_request.body() + try: + payload = json.loads(body) + except json.JSONDecodeError as exc: + raise PlaygroundError(422, "bad_json", f"Request body is not valid JSON: {exc}") + if not isinstance(payload, dict): + raise PlaygroundError(422, "bad_request", "Request body must be a JSON object") + images = payload.get("images", []) + if not isinstance(images, list): + raise PlaygroundError(422, "bad_image", "'images' must be a list of data URLs") + images = list(images) + extract_state_images(payload) # data:image URIs embedded in the state count as images too + blobs = [decode_data_url(value, i) for i, value in enumerate(images)] + else: + raise PlaygroundError(422, "bad_request", + "Use multipart/form-data (field 'request' + files 'image') or application/json") + if not isinstance(payload, dict): + raise PlaygroundError(422, "bad_request", "The request must be a JSON object") + payload = {k: v for k, v in payload.items() if k not in ("images", "model")} + return payload, blobs + + +def decode_images(blobs): + """Zero images is a text-only request; one or two go to the image model. Three is a 422.""" + if len(blobs) > 2: + raise PlaygroundError(422, "bad_image", + f"Provide at most two images (first = reference, second = target); got {len(blobs)}") + loaded = [] + for position, data in enumerate(blobs): + if len(data) > MAX_BYTES: + raise PlaygroundError(413, "image_too_large", f"Image {position} exceeds 20 MiB") + try: + loaded.append(load_image_bytes(data)) + except ValueError as exc: + raise PlaygroundError(_image_status(str(exc)), "bad_image", f"Image {position}: {exc}") + except OSError as exc: + raise PlaygroundError(422, "bad_image", f"Image {position} could not be decoded: {exc}") + return loaded + + +def compile_payload(payload, max_options=MAX_OPTIONS): + """-> (internal Request, multi plan). max_options is the loaded readout's limit (254, or 255 with 256 codes).""" + try: + return to_request_with_plan(payload, request_id="playground", max_options=max_options) + except ValidationError as exc: + raise PlaygroundError(422, "invalid_request", "; ".join( + f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in exc.errors()) or str(exc)) + except (ValueError, TypeError) as exc: + raise PlaygroundError(422, "invalid_request", str(exc)) + + +# ------------------------------------------------------------------------------------------- app + +def create_app(backend, examples=None, static=STATIC, calibration=None, thinking=None): + """`backend` needs .name, .model, .adapter, .load_seconds and .score(images, request); a backend with + .supports_thinking also takes .score(images, request, thinking=ThinkingPolicy). `thinking` = the server's default policy + (off unless the server was started with --thinking); a request's "thinking" object overrides it.""" + thinking = thinking or ThinkingPolicy() + app = FastAPI(title="imajev playground", docs_url="/docs", redoc_url=None) + app.state.backend = backend + app.state.examples = load_examples() if examples is None else examples + app.state.lock = threading.Lock() + + @app.exception_handler(PlaygroundError) + async def playground_error(request, exc): + return JSONResponse({"error": exc.error, "detail": exc.detail}, status_code=exc.status) + + @app.exception_handler(RequestValidationError) + async def validation_error(request, exc): + return JSONResponse({"error": "invalid_request", "detail": str(exc)}, status_code=422) + + @app.exception_handler(HTTPException) + async def http_error(request, exc): + return JSONResponse({"error": "http_error", "detail": exc.detail}, status_code=exc.status_code) + + @app.get("/v1/models") + def models(): + body = {"model": backend.model, "adapter": backend.adapter, "backend": backend.name, + "loaded": True, "load_seconds": round(backend.load_seconds, 3)} + for extra in ("readout_codes", "prompt_layout", "max_options"): + if hasattr(backend, extra): + body[extra] = getattr(backend, extra) + return body + + @app.get("/examples") + def examples_index(): + return app.state.examples + + @app.get("/examples/{example}/image/{index}") + def example_image(example: int, index: int): + items = app.state.examples + if not 0 <= example < len(items) or not 0 <= index < len(items[example]["images"]): + raise PlaygroundError(404, "not_found", "No such example image") + path = ROOT / items[example]["images"][index]["path"] + if not path.is_file(): + raise PlaygroundError(404, "not_found", "Example image is missing from this checkout") + media = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + return FileResponse(path, media_type=media, headers={"Cache-Control": "no-cache"}) + + @app.post("/v1/systemone") + async def systemone(http_request: HttpRequest): + started = perf_counter() + payload, blobs = await read_payload(http_request) + loaded = decode_images(blobs) + request, plan = compile_payload(payload, getattr(backend, "max_options", MAX_OPTIONS)) + images = [image for image, _ in loaded] # [] is a text-only request; the model handles it + try: + policy = thinking.with_request(payload.get("thinking")) + except (TypeError, ValueError) as exc: + raise PlaygroundError(422, "invalid_request", str(exc)) + if policy.active and not getattr(backend, "supports_thinking", False): + raise PlaygroundError(422, "invalid_request", f"thinking is not available on the {backend.name} backend") + + def run(): + with app.state.lock: # one GPU: strictly sequential + return backend.score(images, request, thinking=policy) if policy.active else backend.score(images, request) + + try: + results, usage = await run_in_threadpool(run) + except PlaygroundError: + raise + except Exception as exc: + log.exception("scoring failed") + raise PlaygroundError(500, type(exc).__name__, str(exc)) + if calibration is not None: + photo_only = bool(images) and not request.state # images with no record: schema-1.2 files carry their own temperature + results = [calibration.calibrate_result(result, field.type, len(result.scores) - 1, image=bool(images), photo_only=photo_only) + for field, result in zip(request.fields, results)] + body = to_response(request, results, model=backend.model, plan=plan) + total_ms = round((perf_counter() - started) * 1000, 1) + body["usage"] = {**usage, "total_ms": total_ms, + "images": [{k: meta[k] for k in ("sha256", "width", "height")} for _, meta in loaded]} + abstained = sum(1 for answer in body["answers"].values() if answer["abstained"]) + log.info("%s images=%d questions=%d total_ms=%.1f abstained=%d", + datetime.now(timezone.utc).isoformat(timespec="milliseconds"), + len(images), len(request.fields), total_ms, abstained) + return body + + static = Path(static) + if static.is_dir(): + app.mount("/", StaticFiles(directory=str(static), html=True), name="static") + else: + @app.get("/", response_class=HTMLResponse) + def placeholder(): + return ("imajev playground" + "

Playground UI not built yet — the API is at POST /v1/systemone.

") + return app + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="playground-server", description=__doc__) + parser.add_argument("--backend", choices=("auto", "mlx", "torch"), default="auto") + parser.add_argument("--adapter", help="override the adapter directory") + parser.add_argument("--no-adapter", action="store_true", help="serve the base model") + parser.add_argument("--model-bundle", default=str(BUNDLE)) + parser.add_argument("--rotations", type=int, default=1, help="candidate orders averaged per question (MLX and torch)") + parser.add_argument("--calibration", help="held-out temperature calibration artifact") + parser.add_argument("--max-input-tokens", type=int, default=4096, + help="refuse requests longer than this many processed tokens (training used <= 4096)") + parser.add_argument("--model-name", help="public model name reported by the API and the UI (e.g. imajev-2b)") + parser.add_argument("--readout-codes", type=int, choices=(255, 256), + help="decision readout size; default = the adapter's. 256 extends a 255-code adapter by one " + "LM-head-initialised code so choice questions may have 255 options") + parser.add_argument("--prompt-layout", choices=("auto", "standard", "compact"), default="auto", + help="prompt layout; auto = the layout recorded in the adapter (standard when absent)") + parser.add_argument("--fast", action="store_true", + help="torch only: tokenize once and, on CUDA, replay recorded graphs of the language model " + "(captured at load, about a minute); same decisions as without it") + parser.add_argument("--merge-lora", action="store_true", + help="torch only: fold the LoRA into the weights at load (a little faster; bf16 rounding can move " + "near-tie decisions)") + parser.add_argument("--thinking", choices=("off", "auto", "always"), default="off", + help="default thinking mode (torch only); a request's \"thinking\" object overrides it. auto thinks only " + "when the single-pass answer is unsure (docs/think-if-unsure-plan.md)") + parser.add_argument("--think-max-tokens", type=int, default=256, help="default thought budget in tokens") + parser.add_argument("--think-threshold", type=float, default=0.7, + help="auto: think when the top option's share of the non-unknown mass is below this") + parser.add_argument("--think-unknown-threshold", type=float, default=None, + help="auto: also think when the unknown mass is above this (default: not used)") + parser.add_argument("--think-engine", choices=("hf", "vllm"), default="hf", + help="who writes thoughts: transformers generate in this process (hf), or a vLLM OpenAI server running " + "the same merged weights (vllm; see scripts/export_merged.py)") + parser.add_argument("--think-url", default="http://127.0.0.1:8000", help="--think-engine vllm: the vLLM server") + parser.add_argument("--think-model", default="imajev-4b", help="--think-engine vllm: its served model name") + parser.add_argument("--float32", action="store_true", + help="torch only: serve in float32 on CUDA too (a slow reference for checking bf16 serving paths)") + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8765) + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout) + backend = build_backend(args.backend, args.adapter, args.no_adapter, Path(args.model_bundle), args.rotations, + args.max_input_tokens, readout_codes=args.readout_codes, + prompt_layout=None if args.prompt_layout == "auto" else args.prompt_layout, fast=args.fast, + merge_lora=args.merge_lora, float32=args.float32) + if args.model_name: + backend.model = args.model_name + log.info("backend=%s model=%s adapter=%s load_seconds=%.1f readout_codes=%s prompt_layout=%s", + backend.name, backend.model, backend.adapter, backend.load_seconds, backend.readout_codes, backend.prompt_layout) + calibration = None + if args.calibration: + from vision_decision.calibration import TemperatureCalibrator + calibration = TemperatureCalibrator.load(args.calibration) + import uvicorn + thinking = ThinkingPolicy(mode=args.thinking, max_tokens=args.think_max_tokens, threshold=args.think_threshold, + unknown_threshold=args.think_unknown_threshold) + if thinking.active and not getattr(backend, "supports_thinking", False): + parser.error(f"--thinking needs the torch backend (this server runs {backend.name})") + if args.think_engine == "vllm": + if not getattr(backend, "supports_thinking", False): + parser.error("--think-engine vllm needs the torch backend") + from thought_engine import VLLMThoughts + backend.thoughts = VLLMThoughts(args.think_url, args.think_model, backend.engine.processor.tokenizer) + uvicorn.run(create_app(backend, calibration=calibration, thinking=thinking), host=args.host, port=args.port, log_level="warning") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/upstream/scripts/torch_decision.py b/upstream/scripts/torch_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..78d96a65056b68f88d0c083d77449007736a259d --- /dev/null +++ b/upstream/scripts/torch_decision.py @@ -0,0 +1,289 @@ +"""PyTorch twin of the MLX decision path, for cloud GPUs. Same prompt, same decision position, same float32 candidate head.""" +from pathlib import Path +import json +import torch +from vision_decision.scoring import MAX_READOUT_CODES, DEFAULT_PROMPT_LAYOUT, check_prompt_layout, check_readout_codes, readout_codes, verified_label_ids + +TARGETS=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj','in_proj_qkv','in_proj_z','out_proj'] + +class _LazyMultimodalProcessor: + """Text requests need only the tokenizer; load optional vision/video processors on demand.""" + def __init__(self,path): + from transformers import AutoTokenizer + self.path=path;self.tokenizer=AutoTokenizer.from_pretrained(path,local_files_only=True);self._multimodal=None + def _vision(self): + if self._multimodal is None: + from transformers import AutoProcessor + self._multimodal=AutoProcessor.from_pretrained(self.path,local_files_only=True) + self._multimodal.tokenizer=self.tokenizer # preserve padding-side changes made by collate() + return self._multimodal + def apply_chat_template(self,messages,**kwargs): + if any(item.get('type') in ('image','video') for message in messages for item in message.get('content',[]) if isinstance(item,dict)): + return self._vision().apply_chat_template(messages,**kwargs) + return self.tokenizer.apply_chat_template(messages,**kwargs) + def __call__(self,text,images=None,**kwargs): + if images is not None:return self._vision()(text=text,images=images,**kwargs) + kwargs.setdefault('add_special_tokens',False) + return self.tokenizer(text,**kwargs) + def __getattr__(self,name): + if name.startswith('_'):raise AttributeError(name) + return getattr(self._vision(),name) + +class TorchDecision: + def __init__(self,path,device,dtype=torch.bfloat16,max_length=4096,pad_multiple=0): + from transformers import Qwen3_5ForConditionalGeneration + self.processor=_LazyMultimodalProcessor(path);self.device=device;self.max_length=max_length;self.pad_multiple=pad_multiple # pad batches to a multiple (fewer distinct kernel shapes) + self.model=Qwen3_5ForConditionalGeneration.from_pretrained(path,local_files_only=True,dtype=dtype).to(device).eval() + self.readout=None;self._codebook=None + self.codes=MAX_READOUT_CODES # readout size: 255 shipped; 256 with the extended readout (enable_readout(codes=256)) + self.prompt_layout=DEFAULT_PROMPT_LAYOUT # set from the adapter's decision_readout.json, or by the trainer + def add_lora(self,rank=16,alpha=32,targets=None): + from peft import LoraConfig,get_peft_model + # Language layers only, as in the MLX run; the vision tower stays frozen. `targets` narrows the module list (e.g. attention only). + self.model=get_peft_model(self.model,LoraConfig(r=rank,lora_alpha=alpha,lora_dropout=0.0,target_modules=r'.*language_model.*\.('+'|'.join(targets or TARGETS)+')')) + return self.model + def _ensure_codebook(self,n_images=0): + if self._codebook is None or len(self._codebook)!=self.codes:self._codebook=readout_codes(self.processor.tokenizer,self.render('',n_images),self.codes,limit=self.codes) + return self._codebook + def labels(self,count,n_images=0): + codebook=self._ensure_codebook(n_images) + if count>len(codebook):raise ValueError(f'{count} candidates exceed the {len(codebook)}-code readout (at most {len(codebook)-1} options + unknown)') + return [x[0] for x in codebook[:count]] + @property + def max_options(self):return self.codes-1 + def enable_readout(self,adapter=None,trainable=True,codes=None): + """Install the decision readout Linear[codes, hidden], initialized from the matching LM-head rows. + + codes: 255 (shipped) or 256 (extended); None = the adapter's own row count (255 without an adapter). + A 255-row trained readout loaded with codes=256 gets row 256 appended from its LM-head row, exactly as + the original rows were initialized, so questions with <= 254 options use unchanged rows. + The adapter's prompt layout (decision_readout.json "prompt_layout", absent = standard) is adopted. + Older adapters omit decision_readout.safetensors and continue through vocabulary rows. + """ + from safetensors.torch import load_file + base=self.model.get_base_model() if hasattr(self.model,'get_base_model') else self.model + trained=manifest=None + if adapter is not None: + path=Path(adapter)/'decision_readout.safetensors' + if not path.exists():return False + trained=load_file(str(path),device=str(self.device))['weight'].float() + manifest_path=Path(adapter)/'decision_readout.json' + if not manifest_path.exists():raise ValueError('Trained readout is missing decision_readout.json tokenizer binding') + manifest=json.loads(manifest_path.read_text()) + rows=trained.shape[0] if trained is not None and trained.ndim==2 else None + wanted=check_readout_codes(codes if codes is not None else rows if rows in (255,256) else MAX_READOUT_CODES) + if trained is not None and rows not in (255,256):raise ValueError('Decision readout must be finite with shape [255 or 256, hidden_size]') + if rows is not None and rows>wanted:raise ValueError(f'This adapter has a {rows}-code readout; load it with codes={rows}') + self.codes=wanted;self._codebook=None;codebook=self._ensure_codebook(0) + ids=[x[1] for x in codebook] + weight=base.lm_head.weight[torch.tensor(ids,device=self.device)].detach().float().clone() + if trained is not None: + actual=[{'code':c,'token_id':i} for c,i in codebook] + bound=manifest.get('codes') + if manifest.get('version')!=1 or not isinstance(bound,list) or len(bound)!=rows or bound!=actual[:rows]:raise ValueError('Decision readout code/token binding does not match this tokenizer') + weight=torch.cat([trained,weight[rows:]]) if rows\n\n\n\n'):raise ValueError('Unexpected Qwen non-thinking template boundary') + return rendered + def prepare(self,images,prompt,labels): + images=[] if images is None else images if isinstance(images,list) else [images];rendered=self.render(prompt,len(images)) + token_ids=verified_label_ids(self.processor.tokenizer,rendered,labels) + inputs=self.processor(text=[rendered],images=images or None,return_tensors='pt') + if inputs['input_ids'].shape[-1]>self.max_length:raise ValueError(f'Processed request exceeds the {self.max_length}-token limit') + suffix=self.processor.tokenizer.encode('\n\n',add_special_tokens=False) + if inputs['input_ids'][0,-len(suffix):].tolist()!=suffix:raise ValueError('Processed decision-position suffix mismatch') + return rendered,inputs,token_ids + def candidate_logits(self,inputs,token_ids): + inputs={k:v.to(self.device) for k,v in inputs.items()};base=self.model.get_base_model() if hasattr(self.model,'get_base_model') else self.model + hidden=base.model(**inputs).last_hidden_state[0,-1] + indices=self._readout_indices(token_ids) + return self.readout(hidden.float()) [indices] if self.readout is not None and indices is not None else hidden.float()@base.lm_head.weight[torch.tensor(token_ids,device=self.device)].float().T + def _readout_indices(self,token_ids): + if self._codebook is None:return None + lookup={token:i for i,(_,token) in enumerate(self._codebook)} + return [lookup[x] for x in token_ids] if all(x in lookup for x in token_ids) else None + + # ---- batched path (keeps large GPUs busy): left padding puts every decision position at index -1 ---- + def render_example(self,images,prompt,labels): + """CPU-only half of prepare(): safe to run in DataLoader workers.""" + images=[] if images is None else images if isinstance(images,list) else [images];rendered=self.render(prompt,len(images)) + return rendered,images,verified_label_ids(self.processor.tokenizer,rendered,labels) + def collate(self,examples): + """examples: (rendered, images, token_ids, target). Returns model inputs plus per-example label ids and targets.""" + self.processor.tokenizer.padding_side='left' + image_groups=[e[1] for e in examples] + images=None if all(not group for group in image_groups) else image_groups + inputs=self.processor(text=[e[0] for e in examples],images=images,return_tensors='pt',padding=True,**({'pad_to_multiple_of':self.pad_multiple} if self.pad_multiple else {})) + if inputs['input_ids'].shape[-1]>self.max_length:raise ValueError(f'Processed request exceeds the {self.max_length}-token limit') + suffix=self.processor.tokenizer.encode('\n\n',add_special_tokens=False) + if not all(row[-len(suffix):].tolist()==suffix for row in inputs['input_ids']):raise ValueError('Left padding did not align the decision positions') + return inputs,[e[2] for e in examples],[e[3] for e in examples] + def candidate_logits_batch(self,inputs,token_ids): + inputs={k:v.to(self.device) for k,v in inputs.items()};base=self.model.get_base_model() if hasattr(self.model,'get_base_model') else self.model + hidden=base.model(**inputs).last_hidden_state[:,-1].float();head=base.lm_head.weight + result=[] + for i,ids in enumerate(token_ids): + indices=self._readout_indices(ids) + result.append(self.readout(hidden[i])[indices] if self.readout is not None and indices is not None else hidden[i]@head[torch.tensor(ids,device=self.device)].float().T) + return result + def candidate_logits_with_rationale(self,inputs,token_ids,position,labels): + """--rationale-weight path: candidate logits read at `position` (the decision position, unchanged by the + appended rationale block under causal attention) plus the per-example rationale LM loss [B].""" + from decision_recipe import rationale_lm_loss + inputs={k:v.to(self.device) for k,v in inputs.items()};base=self.model.get_base_model() if hasattr(self.model,'get_base_model') else self.model + states=base.model(**inputs).last_hidden_state;hidden=states[:,position].float();head=base.lm_head.weight + result=[] + for i,ids in enumerate(token_ids): + indices=self._readout_indices(ids) + result.append(self.readout(hidden[i])[indices] if self.readout is not None and indices is not None else hidden[i]@head[torch.tensor(ids,device=self.device)].float().T) + return result,rationale_lm_loss(states,head,labels,position+1) + + # ---- serving fast path (server --fast): same decision function, less work per request ---- + def merge_adapter(self,adapter,dtype=torch.bfloat16): + """Fold a PEFT LoRA into the weights so every forward is a plain base-model forward. Call on a float32 model: the + low-rank sum is formed in float32 and rounded once to `dtype`. The decision readout is separate and stays float32.""" + from peft import PeftModel + self.model=PeftModel.from_pretrained(self.model,str(adapter)).merge_and_unload().to(dtype).eval() + DECISION_TAIL='\n\n' + def label_ids(self,rendered,labels): + """= verified_label_ids(tokenizer, rendered, labels), with one tokenization per label for the life of the process. + The rendered prompt ends with the special token '' then '\\n\\n'; the tokenizer splits at special tokens, so + whether a label is one token at the decision position depends only on that tail (test_torch_fast_path checks this).""" + if not rendered.endswith(self.DECISION_TAIL):return verified_label_ids(self.processor.tokenizer,rendered,labels) + cache=self.__dict__.setdefault('_label_cache',{}) + for label in labels: + if label not in cache:cache[label]=verified_label_ids(self.processor.tokenizer,self.DECISION_TAIL,[label])[0] + ids=[cache[label] for label in labels] + if len(set(ids))!=len(ids):raise ValueError('Choice labels do not have distinct token IDs') + return ids + def prepare_fast(self,images,prompt,labels): + """prepare() with one tokenization: text-only requests skip the multimodal processor (same ids, checked by the test).""" + images=[] if images is None else images if isinstance(images,list) else [images];rendered=self.render(prompt,len(images)) + token_ids=self.label_ids(rendered,labels) + # Images: the processor resizes and patchifies as always but leaves the pixels as uint8; normalize_patches finishes the + # identical float32 arithmetic on the GPU (8x fewer bytes to copy, no float work on the CPU). + inputs=dict(self.processor(text=[rendered],images=images,return_tensors='pt',do_rescale=False,do_normalize=False)) if images else {'input_ids':self.processor.tokenizer(rendered,add_special_tokens=False,return_tensors='pt')['input_ids']} + if inputs['input_ids'].shape[-1]>self.max_length:raise ValueError(f'Processed request exceeds the {self.max_length}-token limit') + suffix=self.__dict__.get('_suffix_ids') or self.__dict__.setdefault('_suffix_ids',self.processor.tokenizer.encode(self.DECISION_TAIL,add_special_tokens=False)) + if inputs['input_ids'][0,-len(suffix):].tolist()!=suffix:raise ValueError('Processed decision-position suffix mismatch') + return rendered,inputs,token_ids + def normalize_patches(self,patches): + """The image processor's rescale_and_normalize on already patchified uint8 pixels: one fused mean and std per channel, + then x.float() - mean, / std, exactly the torchvision normalize the processor runs before patchify. Elementwise, so + patchify first changes nothing; each patch row is channel-major (channel x temporal x patch x patch).""" + ip=self.processor.image_processor + mean,std,_=ip._fuse_mean_std_and_rescale_factor(do_normalize=True,image_mean=ip.image_mean,image_std=ip.image_std,do_rescale=True,rescale_factor=ip.rescale_factor,device=patches.device) + per=ip.temporal_patch_size*ip.patch_size*ip.patch_size + mean=torch.as_tensor(mean,dtype=torch.float32,device=patches.device).repeat_interleave(per);std=torch.as_tensor(std,dtype=torch.float32,device=patches.device).repeat_interleave(per) + return patches.to(torch.float32).sub_(mean).div_(std) + def _base(self): + """The Qwen3.5 model under a PEFT wrapper (its LoRA layers stay in place) or the merged model itself.""" + return self.model.get_base_model() if hasattr(self.model,'get_base_model') else self.model + def _embeds_positions(self,inputs): + """The multimodal model's forward up to the language model: token embeddings with the image features scattered in, and the + M-RoPE position ids (3 x 1 x n). Text-only positions are 0..n-1 on every axis, as the model's own default.""" + m=self._base().model;ids=inputs['input_ids'];embeds=m.get_input_embeddings()(ids) + if 'pixel_values' not in inputs:return embeds,torch.arange(ids.shape[1],device=ids.device).view(1,1,-1).expand(3,1,-1) + features=torch.cat(m.get_image_features(inputs['pixel_values'],inputs['image_grid_thw'],return_dict=True).pooler_output,dim=0).to(embeds.device,embeds.dtype) + mask,_=m.get_placeholder_mask(ids,inputs_embeds=embeds,image_features=features);embeds=embeds.masked_scatter(mask,features) + positions=m.compute_3d_position_ids(input_ids=ids,inputs_embeds=embeds,image_grid_thw=inputs['image_grid_thw'],attention_mask=inputs.get('attention_mask'),mm_token_type_ids=inputs.get('mm_token_type_ids')) + return embeds,positions + def candidate_logits_fast(self,inputs,token_ids): + """candidate_logits(), through a recorded CUDA graph when one fits the prompt length.""" + inputs={k:v.to(self.device) for k,v in inputs.items()};base=self._base() + if inputs.get('pixel_values') is not None and inputs['pixel_values'].dtype==torch.uint8:inputs['pixel_values']=self.normalize_patches(inputs['pixel_values']) + embeds,positions=self._embeds_positions(inputs);graphs=self.__dict__.get('graphs') + hidden=graphs.run(embeds,positions) if graphs is not None and graphs.fits(embeds.shape[1]) else base.model.language_model(inputs_embeds=embeds,position_ids=positions,use_cache=False).last_hidden_state[0,-1] + indices=self._readout_indices(token_ids) + return self.readout(hidden.float())[indices] if self.readout is not None and indices is not None else hidden.float()@base.lm_head.weight[torch.tensor(token_ids,device=self.device)].float().T + def capture_graphs(self,lengths): + base=self._base() + self.graphs=DecoderGraphs(base.model.language_model,base.config.text_config.hidden_size,lengths,self.device,base.dtype) + return self.graphs + + # ---- thinking (think-if-unsure): a greedy thought in Qwen3.5's thinking template, the decision read right after it ---- + THINK_TAIL='\n' + def render_thinking(self,prompt,n_images): + messages=[dict(role='user',content=[dict(type='image')]*n_images+[dict(type='text',text=prompt)])] + rendered=self.processor.apply_chat_template(messages,add_generation_prompt=True,tokenize=False,enable_thinking=True) + if not rendered.endswith(self.THINK_TAIL):raise ValueError('Unexpected Qwen thinking template boundary') + return rendered + def _thinking_inputs(self,images,prompt): + images=[] if images is None else images if isinstance(images,list) else [images] + inputs=dict(self.processor(text=[self.render_thinking(prompt,len(images))],images=images or None,return_tensors='pt')) + if inputs['input_ids'].shape[-1]>self.max_length:raise ValueError(f'Processed request exceeds the {self.max_length}-token limit') + return inputs + def think_end_id(self): + ids=self.processor.tokenizer.encode('',add_special_tokens=False) + if len(ids)!=1:raise ValueError("'' is not a single token") + return ids[0] + @torch.inference_mode() + def generate_thought(self,images,prompt,max_tokens): + """Greedy thought token ids (without '') and whether the model closed the thought itself.""" + tok=self.processor.tokenizer;end=self.think_end_id();pad=tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id + inputs={k:v.to(self.device) for k,v in self._thinking_inputs(images,prompt).items()} + out=self.model.generate(**inputs,max_new_tokens=int(max_tokens),do_sample=False,eos_token_id=[end,tok.eos_token_id],pad_token_id=pad) + tokens=[] + for token in out[0,inputs['input_ids'].shape[-1]:].tolist(): + if token==end:return tokens,True + if token in (tok.eos_token_id,pad):break + tokens.append(token) + return tokens,False + def inputs_after_thought(self,images,prompt,labels,thought,closed): + """Model inputs ending '\\n\\n' after `thought` (token ids; a cut thought is closed with '\\n\\n\\n'), + and the labels' token ids at that decision position. Same image, prompt and decision position as the single pass.""" + images=[] if images is None else images if isinstance(images,list) else [images] + inputs=self._thinking_inputs(images,prompt);tok=self.processor.tokenizer + tail=tok.encode('\n\n' if closed else '\n\n\n',add_special_tokens=False) + extra=torch.tensor([list(thought)+tail],dtype=inputs['input_ids'].dtype) + inputs['input_ids']=torch.cat([inputs['input_ids'],extra],dim=1) + if 'attention_mask' in inputs:inputs['attention_mask']=torch.cat([inputs['attention_mask'],torch.ones_like(extra)],dim=1) + if 'mm_token_type_ids' in inputs:inputs['mm_token_type_ids']=torch.cat([inputs['mm_token_type_ids'],torch.zeros_like(extra,dtype=inputs['mm_token_type_ids'].dtype)],dim=1) + if inputs['input_ids'].shape[-1]>self.max_length:raise ValueError(f'Processed request exceeds the {self.max_length}-token limit') + suffix=tok.encode(self.DECISION_TAIL,add_special_tokens=False) + if inputs['input_ids'][0,-len(suffix):].tolist()!=suffix:raise ValueError('Decision-position suffix mismatch after the thought') + return inputs,self.label_ids(self.DECISION_TAIL,labels) + +GRAPH_LENGTHS=list(range(64,1025,64))+list(range(1152,2049,128))+list(range(2304,4097,256)) + +class DecoderGraphs: + """CUDA graphs of the language model at fixed padded lengths, recorded once at load (the design of JevK5's runtime, + Apache-2.0, also used by FlyMy's Decision 4B). A prompt is right-padded to the next recorded length: every layer is + causal (full attention, gated DeltaNet, its short convolution), so padding after the decision position cannot change it.""" + def __init__(self,lm,hidden,lengths,device,dtype): + self.graphs={};pool=None + with torch.inference_mode(): + for n in sorted(set(lengths),reverse=True): # longest first: the shorter graphs reuse its memory pool + embeds=torch.zeros(1,n,hidden,device=device,dtype=dtype);positions=torch.arange(n,device=device).view(1,1,n).expand(3,1,n).contiguous() + last=torch.zeros(1,dtype=torch.long,device=device) + def step(embeds=embeds,positions=positions,last=last): + return lm(inputs_embeds=embeds,position_ids=positions,use_cache=False).last_hidden_state[0].index_select(0,last)[0] + side=torch.cuda.Stream();side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + for _ in range(3):step() # warm-up: compiles the Triton kernels outside the capture + torch.cuda.current_stream().wait_stream(side) + graph=torch.cuda.CUDAGraph() + with torch.cuda.graph(graph,pool=pool):out=step() + pool=graph.pool();self.graphs[n]=(graph,embeds,positions,last,out) + self.lengths=sorted(self.graphs) + def fits(self,n):return bool(self.lengths) and n<=self.lengths[-1] + def run(self,embeds,positions): + n=embeds.shape[1];size=next(x for x in self.lengths if x>=n);graph,static_embeds,static_positions,last,out=self.graphs[size] + static_embeds.zero_();static_embeds[:,:n].copy_(embeds) + static_positions[:,:,:n].copy_(positions);static_positions[:,:,n:].copy_(positions[:,:,-1:]+torch.arange(1,size-n+1,device=positions.device)) + last.fill_(n-1);graph.replay() + return out.clone() diff --git a/upstream/src/vision_decision/__init__.py b/upstream/src/vision_decision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3162d6f4716be20fd9a5cc3c78aa3252159120 --- /dev/null +++ b/upstream/src/vision_decision/__init__.py @@ -0,0 +1 @@ +"""Vision Decision Engine. Research-only, uncalibrated predictions.""" diff --git a/upstream/src/vision_decision/backend.py b/upstream/src/vision_decision/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..af3e905f899d532c9cbe5e88930f9c7f23162406 --- /dev/null +++ b/upstream/src/vision_decision/backend.py @@ -0,0 +1,313 @@ +"""MLX direct-choice prototype; one unpadded request per forward pass.""" +import hashlib +import json +from pathlib import Path +from time import perf_counter +from .scoring import (MAX_READOUT_CODES, DEFAULT_PROMPT_LAYOUT, check_prompt_layout, check_readout_codes, compile_question, + readout_codes, verified_label_ids, result_from_logits, cyclic_offsets, rotate, combine_rotations) + +class MLXDirect: + def __init__(self, bundle="artifacts/model.json", adapter=None, max_input_tokens=4096, readout_codes=None, prompt_layout=None): + """readout_codes: 255 (shipped) or 256 (extended); None = the adapter readout's own row count. + A 255-row trained readout loaded with readout_codes=256 gets row 256 appended from its LM-head row. + prompt_layout: None = the layout recorded in the adapter's decision_readout.json (absent = standard).""" + import mlx.core as mx + self.max_input_tokens = int(max_input_tokens) + from mlx_vlm import load + self.mx = mx + self.bundle = json.loads(Path(bundle).read_text()) + if not Path(self.bundle["path"]).is_dir(): + raise ValueError("Local model snapshot is missing; run scripts/download_model.py") + start = perf_counter() + self.model, self.processor = load(self.bundle["path"], trust_remote_code=False) + if adapter is not None: + from mlx_vlm.trainer.utils import apply_lora_layers + self.model = apply_lora_layers(self.model, adapter) + self.adapter = None if adapter is None else str(adapter) + self._codebook = None + self.readout = None + self._readout_manifest = {} + rows = None + if adapter is not None: + head = Path(adapter) / "decision_readout.safetensors" + if head.exists(): + weights = mx.load(str(head)) + if (set(weights) != {"weight"} or weights["weight"].ndim != 2 or weights["weight"].shape[0] not in (255, 256) + or not bool(mx.all(mx.isfinite(weights["weight"])).item())): + raise ValueError("Invalid decision_readout.safetensors") + self.readout = weights["weight"] + rows = int(self.readout.shape[0]) + manifest_path = Path(adapter) / "decision_readout.json" + if not manifest_path.exists(): + raise ValueError("Trained readout is missing decision_readout.json tokenizer binding") + self._readout_manifest = json.loads(manifest_path.read_text()) + self.codes = check_readout_codes(readout_codes if readout_codes is not None else rows or MAX_READOUT_CODES) + if rows is not None and rows > self.codes: + raise ValueError(f"This adapter has a {rows}-code readout; load it with readout_codes={rows}") + trained_layout = check_prompt_layout(self._readout_manifest.get("prompt_layout", DEFAULT_PROMPT_LAYOUT)) + self.prompt_layout = trained_layout if prompt_layout is None else check_prompt_layout(prompt_layout) + self.trained_prompt_layout = trained_layout + self._trained_rows = rows + if self.readout is not None and rows < self.codes: + self._extend_readout(rows) + self.model.eval() + mx.eval(self.model.parameters()) + self.load_seconds = perf_counter() - start + + @property + def max_options(self): + return self.codes - 1 + + def _head_rows(self, token_ids): + language = self.model.language_model + head = language.model.embed_tokens if language.args.tie_word_embeddings else language.lm_head + if "scales" in head or "bias" in head: + raise ValueError("Float32 candidate scoring requires an unquantized bias-free output head") + return head.weight[self.mx.array(token_ids)].astype(self.mx.float32) + + def _extend_readout(self, rows): + """Check the trained rows against this tokenizer's codebook; append LM-head rows up to self.codes.""" + from mlx_vlm.prompt_utils import apply_chat_template + rendered = apply_chat_template(self.processor, self.model.config, "", num_images=0, enable_thinking=False) + self._codebook = readout_codes(self.processor.tokenizer, rendered, self.codes, limit=self.codes) + self._check_binding() + if rows < self.codes: # appended rows start from their LM-head rows, exactly as the trained rows did + extra = self._head_rows([token for _, token in self._codebook[rows:]]) + self.readout = self.mx.concatenate([self.readout.astype(self.mx.float32), extra], axis=0) + self.mx.eval(self.readout) + + def _check_binding(self): + bound = self._readout_manifest.get("codes") + actual = [{"code": c, "token_id": i} for c, i in self._codebook] + if (self._readout_manifest.get("version") != 1 or not isinstance(bound, list) + or len(bound) != self._trained_rows or bound != actual[:len(bound)] or len(actual) != self.codes): + raise ValueError("Decision readout code/token binding does not match this tokenizer") + + def score(self, image, field, state): + header, choices, texts = compile_question(field, state, self.prompt_layout) + labels = self._labels(header, len(choices), 0 if image is None else len(image) if isinstance(image, list) else 1) + prompt = header + "\n".join(f"{label}: {text}" for label, text in zip(labels, texts)) + return self.score_compiled(image, prompt, labels, choices) + + def _labels(self, prompt, count, n_images): + if self._codebook is None: + from mlx_vlm.prompt_utils import apply_chat_template + rendered = apply_chat_template(self.processor, self.model.config, prompt, num_images=n_images, enable_thinking=False) + self._codebook = readout_codes(self.processor.tokenizer, rendered, self.codes, limit=self.codes) + if self.readout is not None: + self._check_binding() + if count > len(self._codebook): + raise ValueError(f"{count} candidates exceed the {len(self._codebook)}-code readout " + f"(at most {len(self._codebook) - 1} options + unknown)") + return [code for code, _ in self._codebook[:count]] + + def score_request(self, image, fields, state, rotations=4): + """All fields of one request: one shared prefill, rotated candidate orders per field. + + `image` is one image, a list of one or two, or None/[] for a text-only request. + """ + return self.score_questions(image, [compile_question(field, state, self.prompt_layout) for field in fields], rotations) + + def score_compiled(self, image, prompt, labels, choices): + """Research hook for controlled labels and one- or two-image diagnostics.""" + if len(labels) != len(choices) or not labels: + raise ValueError("Labels and choices must have matching nonzero length") + logits, metadata, _ = self._label_logits(image, prompt, labels) + metadata["tie_break_policy"] = "lowest_vocabulary_token_id" + return result_from_logits(choices, logits, token_ids=metadata["choice_token_ids"]), metadata + + def score_rotated(self, image, header, choices, texts, rotations=4, shared_prefix=True): + """Average candidate log-probabilities over cyclic presentation orders of one question.""" + results, metadata = self.score_questions(image, [(header, choices, texts)], rotations, shared_prefix) + return results[0], metadata["questions"][0] | {k: v for k, v in metadata.items() if k != "questions"} + + def score_questions(self, image, questions, rotations=4, shared_prefix=True): + """Score every (header, choices, texts) question for one image, or for no image at all. + + Each question is shown in up to `rotations` cyclic candidate orders and its + per-candidate log-probabilities are averaged. With shared_prefix the image (when there + is one) and the leading text common to all prompts are evaluated once for the whole + request; a text-only request shares the state and question header the same way. + """ + prompts, owners = [], [] + for index, (header, choices, texts) in enumerate(questions): + if len(texts) != len(choices) or len(choices) < 2: + raise ValueError("Texts and choices must have matching length of at least two") + n_images = 0 if image is None else len(image) if isinstance(image, list) else 1 + labels = self._labels(header, len(choices), n_images) + for offset in cyclic_offsets(len(choices), rotations): + lines = "\n".join(f"{label}: {text}" for label, text in zip(labels, rotate(texts, offset))) + prompts.append((header + lines, labels)) + owners.append((index, offset)) + if shared_prefix: + scored, shared = self._shared_prefix_logits(image, prompts) + else: + scored, shared, features = [], {"shared_prefix_tokens": 0}, None + for prompt, labels in prompts: + logits, metadata, features = self._label_logits(image, prompt, labels, features) + scored.append((logits, metadata)) + results, details = [], [] + for index, (_, choices, _) in enumerate(questions): + passes = [(offset, *scored[k]) for k, (owner, offset) in enumerate(owners) if owner == index] + result = combine_rotations(choices, [(offset, logits) for offset, logits, _ in passes]) + values = list(result.raw_logits.values()) + final = max(range(len(choices)), key=values.__getitem__) + winners = [(max(range(len(logits)), key=logits.__getitem__) + offset) % len(choices) for offset, logits, _ in passes] + results.append(result) + details.append({"rotations": [{"offset": offset, "logits": logits, **meta} for offset, logits, meta in passes], + "rotation_agreement": sum(w == final for w in winners) / len(winners)}) + return results, {"questions": details, "language_model_passes": len(prompts), + "logit_precision": "float32_candidate_head", **shared} + + def _candidate_logits(self, hidden, token_ids, readout_indices=None): + # The BF16 head quantizes logits near 20 to 1/16 steps and creates exact ties; + # project only the candidate rows in float32 instead. + if readout_indices is not None and hasattr(self.model, "decision_readout"): + return self.model.decision_readout(hidden.astype(self.mx.float32))[self.mx.array(readout_indices)] + if readout_indices is not None and self.readout is not None: + return hidden.astype(self.mx.float32) @ self.readout[self.mx.array(readout_indices)].astype(self.mx.float32).T + language = self.model.language_model + head = language.model.embed_tokens if language.args.tie_word_embeddings else language.lm_head + if "scales" in head or "bias" in head: + raise ValueError("Float32 candidate scoring requires an unquantized bias-free output head") + mx = self.mx + return hidden.astype(mx.float32) @ head.weight[mx.array(token_ids)].astype(mx.float32).T + + def _prepare(self, image, prompt, labels): + from mlx_vlm.prompt_utils import apply_chat_template + from mlx_vlm.utils import prepare_inputs + mx = self.mx + start = perf_counter() + images = [] if image is None else (image if isinstance(image, list) else [image]) + if len(images) > 2: + raise ValueError("Research scoring supports at most two images") + rendered = apply_chat_template(self.processor, self.model.config, prompt, num_images=len(images), enable_thinking=False) + # Qwen non-thinking template must close its empty reasoning block before the answer. + if not rendered.endswith("\n\n\n\n"): + raise ValueError("Unexpected Qwen non-thinking template boundary; refusing to score an unverified position") + tokenizer = self.processor.tokenizer + token_ids = verified_label_ids(tokenizer, rendered, labels) + codebook = self._codebook or readout_codes(tokenizer, rendered, self.codes, limit=self.codes) + self._codebook = codebook + if self.readout is not None: + self._check_binding() + lookup = {code: i for i, (code, _) in enumerate(codebook)} + readout_indices = [lookup[x] for x in labels] if all(x in lookup for x in labels) else None + # A text-only request (no image) goes through the same decision position; prepare_inputs + # then returns ids and mask only, so there is no pixel tensor and no image grid to check. + inputs = prepare_inputs(self.processor, images=images or None, prompts=rendered, + image_token_index=self.model.config.image_token_index) + ids = inputs.pop("input_ids") + pixels = inputs.pop("pixel_values", None) + mask = inputs.pop("attention_mask", None) + if ids.shape[0] != 1 or (mask is not None and not bool(mx.all(mask == 1).item())): + raise ValueError("This adapter supports only one unpadded example") + # Verify the actual processed sequence's answer suffix survived image-token expansion. + suffix = tokenizer.encode("\n\n", add_special_tokens=False) + if ids[0, -len(suffix):].tolist() != suffix: + raise ValueError("Processed decision-position suffix mismatch") + if ids.shape[-1] > self.max_input_tokens: + raise ValueError(f"Processed request exceeds the {self.max_input_tokens}-token limit") + if images: + if pixels is None or "image_grid_thw" not in inputs: + raise ValueError("Processor returned no image grid") + grids = inputs["image_grid_thw"].tolist() + if len(grids) != len(images): + raise ValueError("Image grid count mismatch") + if any(g[0] * g[1] * g[2] // 4 > 2048 for g in grids): + raise ValueError("Image exceeds the 2048-visual-token research limit") + else: + if pixels is not None or inputs: + raise ValueError("A text-only request must not carry vision inputs") + grids = [] + metadata = {"preprocess_seconds": perf_counter() - start, "input_tokens": ids.shape[-1], + "choice_token_ids": token_ids, "template_sha256": hashlib.sha256(rendered.encode()).hexdigest(), + "readout_indices": readout_indices, "readout": f"trained_{self.codes}" if self.readout is not None and readout_indices is not None else "language_model_rows", + "template_suffix": rendered[-64:], "logit_precision": "float32_candidate_head", + "image_grid_thw": grids} + return ids, pixels, mask, inputs, metadata + + def _image_features(self, pixels, inputs): + tower = self.model.vision_tower + features, _ = tower(pixels.astype(tower.patch_embed.proj.weight.dtype), inputs["image_grid_thw"]) + self.mx.eval(features) + return features + + def _label_logits(self, image, prompt, labels, image_features=None): + """Uncached reference path: one full forward per prompt.""" + mx = self.mx + ids, pixels, mask, inputs, metadata = self._prepare(image, prompt, labels) + start = perf_counter() + if image_features is None and pixels is not None: # no vision tower on a text-only request + image_features = self._image_features(pixels, inputs) + output = self.model(ids, pixels, mask=mask, cached_image_features=image_features, + return_hidden=True, skip_logits=True, **inputs) + selected = self._candidate_logits(output.hidden_states[-1][0, -1], metadata["choice_token_ids"], metadata["readout_indices"]) + mx.eval(selected) + logits = selected.tolist() + metadata.update(forward_seconds=perf_counter() - start, peak_memory_bytes=mx.get_peak_memory(), + logical_forward_evaluations=1) + del output, selected + return logits, metadata, image_features + + def _shared_prefix_logits(self, image, prompts): + """Score several (prompt, labels) pairs for one image with a single prefill. + + The image (when there is one) and every token the prompts share are evaluated once; + each prompt then continues from a private copy of that cache with only its own + remaining tokens. + """ + mx = self.mx + prepared = [self._prepare(image, prompt, labels) for prompt, labels in prompts] + rows = [p[0][0].tolist() for p in prepared] + shared = min(len(r) for r in rows) - 1 # every prompt keeps at least its decision position + for position in range(shared): + if len({r[position] for r in rows}) != 1: + shared = position + break + config = self.model.config + visual = {config.image_token_index, config.video_token_index} + if shared < 1 or any(token in visual for r in rows for token in r[shared:]): + raise ValueError("Prompts must share the image and a leading text segment") + ids, pixels, mask, inputs, _ = prepared[0] + start = perf_counter() + language = self.model.language_model + prefix = language.make_cache() + features = self._image_features(pixels, inputs) if pixels is not None else None + self.model(ids[:, :shared], pixels, cache=prefix, cached_image_features=features, + skip_logits=True, **inputs) + mx.eval([x for c in prefix for x in c.state if x is not None]) + prefill_seconds = perf_counter() - start + scored = [] + for (ids, _, _, inputs, metadata) in prepared: + start = perf_counter() + branch = language.make_cache() + for source, target in zip(prefix, branch): + state = source.state + target.state = list(state) if isinstance(state, list) else state + positions, _ = language.get_rope_index(ids, inputs.get("image_grid_thw")) + output = language(ids[:, shared:], cache=branch, position_ids=positions, return_hidden=True, skip_logits=True) + selected = self._candidate_logits(output.hidden_states[-1][0, -1], metadata["choice_token_ids"], metadata["readout_indices"]) + mx.eval(selected) + metadata.update(forward_seconds=perf_counter() - start, suffix_tokens=ids.shape[-1] - shared) + scored.append((selected.tolist(), metadata)) + del output, selected, branch + shared_metadata = {"shared_prefix_tokens": shared, "prefill_seconds": prefill_seconds, + "peak_memory_bytes": mx.get_peak_memory()} + return scored, shared_metadata + + def generated_reference(self, image, field, state): + from mlx_vlm import generate + from mlx_vlm.prompt_utils import apply_chat_template + images = [] if image is None else (image if isinstance(image, list) else [image]) + header, choices, texts = compile_question(field, state, self.prompt_layout) + labels = self._labels(header, len(choices), len(images)) + prompt = header + "\n".join(f"{label}: {text}" for label, text in zip(labels, texts)) + rendered = apply_chat_template(self.processor, self.model.config, prompt, num_images=len(images), enable_thinking=False) + start = perf_counter() + output = generate(self.model, self.processor, rendered, image=images or None, max_tokens=8, temperature=0, verbose=False) + answer = output.text.strip() + valid = answer in labels + return {"text": answer, "format_valid": valid, + "value": choices[labels.index(answer)][0] if valid else None, + "seconds": perf_counter() - start} diff --git a/upstream/src/vision_decision/calibration.py b/upstream/src/vision_decision/calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0a8f026cfac2226fa297cdd6276dc6aaf8d209 --- /dev/null +++ b/upstream/src/vision_decision/calibration.py @@ -0,0 +1,296 @@ +"""Temperature calibration for typed decision logits. + +Artifacts contain one positive scalar temperature for each decision-type / option-count +bucket. Option counts exclude the always-present ``__unknown__`` candidate. +""" +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +import math +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + +from .contracts import UNKNOWN, Result + +# The top bucket covers 26..255 options: 255 is reachable only with the extended 256-code readout. Its key keeps +# the name "26-254" so the calibration.json files already shipped keep matching (the name is a label, not a bound). +BUCKETS = ((2, 2), (3, 5), (6, 10), (11, 25), (26, 255)) +BUCKET_LABELS = ("2", "3-5", "6-10", "11-25", "26-254") +SHIPPED_MAX_OPTIONS = 254 # 255-code readout: options + unknown +EXTENDED_MAX_OPTIONS = 255 # 256-code readout (phase-3 switch) + + +def option_count_bucket(option_count: int, max_options: int = SHIPPED_MAX_OPTIONS) -> str: + """Bucket label for an option count. max_options is the readout's limit (254 shipped, 255 extended).""" + if isinstance(option_count, bool) or not isinstance(option_count, int) or option_count < 2: + raise ValueError("option_count must be an integer >= 2") + if max_options not in (SHIPPED_MAX_OPTIONS, EXTENDED_MAX_OPTIONS): + raise ValueError(f"max_options must be {SHIPPED_MAX_OPTIONS} or {EXTENDED_MAX_OPTIONS}") + if option_count <= max_options: + for (low, high), label in zip(BUCKETS, BUCKET_LABELS): + if option_count <= high: + return label + raise ValueError(f"option_count plus unknown exceeds the {max_options + 1}-code readout") + + +def calibration_key(decision_type: str, option_count: int, max_options: int = SHIPPED_MAX_OPTIONS) -> str: + if decision_type not in {"choice", "boolean", "ordinal", "noul", "score"}: + raise ValueError(f"Unsupported decision type {decision_type!r}") + canonical = {"noul": "boolean", "score": "ordinal"}.get(decision_type, decision_type) + return f"{canonical}:{option_count_bucket(option_count, max_options)}" + + +def softmax(logits: Sequence[float], temperature: float = 1.0) -> list[float]: + if not logits or not math.isfinite(temperature) or temperature <= 0: + raise ValueError("Expected logits and a finite positive temperature") + scaled = [float(value) / temperature for value in logits] + if not all(math.isfinite(value) for value in scaled): + raise ValueError("Logits must be finite") + top = max(scaled) + weights = [math.exp(value - top) for value in scaled] + total = sum(weights) + return [value / total for value in weights] + + +def _nll(log_temperature: float, samples: Sequence[tuple[Sequence[float], int]], unknown_offset: float = 0.0) -> float: + temperature = math.exp(log_temperature) + loss = 0.0 + for logits, target in samples: + probabilities = softmax(_offset(logits, unknown_offset), temperature) + loss -= math.log(max(probabilities[target], 1e-300)) + return loss / len(samples) + + +def _offset(logits: Sequence[float], unknown_offset: float) -> list[float]: + """Add ``unknown_offset`` to the unknown logit, which is always the last candidate.""" + values = [float(value) for value in logits] + if unknown_offset: + values[-1] += unknown_offset + return values + + +def fit_unknown_offset_and_temperature(samples: Iterable[tuple[Sequence[float], int]], *, + offsets: Sequence[float] = tuple(x / 10 for x in range(-40, 21)), + max_temperature: float = 100.0) -> tuple[float, float]: + """Grid-search an additive unknown-logit offset, refitting the temperature at each point; returns (offset, temperature). + + The offset moves the abstention boundary (it can change the argmax); the temperature then only reshapes confidence. + Both are chosen by held-out NLL on the calibration fold, so a model that abstains too often gets a negative offset. + """ + checked = [(tuple(float(v) for v in logits), target) for logits, target in samples] + if not checked: + raise ValueError("Cannot fit an offset without calibration samples") + best: tuple[float, float, float] | None = None + for offset in offsets: + temperature = fit_temperature([(_offset(logits, offset), target) for logits, target in checked], + max_temperature=max_temperature) + loss = _nll(math.log(temperature), checked, offset) + if best is None or loss < best[0] - 1e-9: + best = (loss, offset, temperature) + assert best is not None + return best[1], best[2] + + +def fit_temperature(samples: Iterable[tuple[Sequence[float], int]], *, max_temperature: float = 100.0) -> float: + """Fit a scalar temperature by bounded one-dimensional held-out NLL minimization.""" + checked: list[tuple[tuple[float, ...], int]] = [] + for logits, target in samples: + values = tuple(float(value) for value in logits) + if len(values) < 2 or not all(math.isfinite(value) for value in values): + raise ValueError("Each sample needs at least two finite logits") + if isinstance(target, bool) or not isinstance(target, int) or not 0 <= target < len(values): + raise ValueError("Target index is outside its candidate logits") + checked.append((values, target)) + if not checked: + raise ValueError("Cannot fit a temperature without calibration samples") + if not math.isfinite(max_temperature) or max_temperature <= 1: + raise ValueError("max_temperature must be finite and > 1") + + # Golden-section search in log space. Bounds prevent a separable fold from yielding 0 or infinity. + lo, hi = math.log(1e-2), math.log(max_temperature) + ratio = (math.sqrt(5.0) - 1.0) / 2.0 + left, right = hi - ratio * (hi - lo), lo + ratio * (hi - lo) + f_left, f_right = _nll(left, checked), _nll(right, checked) + for _ in range(96): + if f_left <= f_right: + hi, right, f_right = right, left, f_left + left = hi - ratio * (hi - lo) + f_left = _nll(left, checked) + else: + lo, left, f_left = left, right, f_right + right = lo + ratio * (hi - lo) + f_right = _nll(right, checked) + candidates = ((0.0, _nll(0.0, checked)), (left, f_left), (right, f_right)) + return math.exp(min(candidates, key=lambda item: item[1])[0]) + + +@dataclass(frozen=True) +class TemperatureCalibrator: + """Per-bucket temperatures, plus optional per-bucket additive offsets on the unknown logit. + + Offsets are fitted on the text-only calibration fold and are applied to text-only requests only + (``image=False``); requests carrying images keep the raw abstention boundary. + """ + version: str + temperatures: Mapping[str, float] + counts: Mapping[str, int] + unknown_offsets: Mapping[str, float] | None = None + # schema 1.2: separate temperatures for photo-only requests (images present, empty state), fitted on + # photo-only verification rows; requests that carry a record keep the base temperatures. + photo_only_temperatures: Mapping[str, float] | None = None + photo_only_counts: Mapping[str, int] | None = None + + def __post_init__(self) -> None: + if not self.version or not isinstance(self.version, str): + raise ValueError("Calibration version must be a non-empty string") + if set(self.counts) != set(self.temperatures): + raise ValueError("Temperature and count buckets must match") + if self.unknown_offsets is not None: + if set(self.unknown_offsets) - set(self.temperatures): + raise ValueError("Unknown offsets must only name temperature buckets") + for value in self.unknown_offsets.values(): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError("Invalid unknown offset artifact") + for key, value in self.temperatures.items(): + if (not isinstance(key, str) or isinstance(value, bool) or not isinstance(value, (int, float)) + or not math.isfinite(value) or value <= 0): + raise ValueError("Invalid temperature artifact") + if (isinstance(self.counts[key], bool) or not isinstance(self.counts[key], int) + or self.counts[key] < 1): + raise ValueError("Calibration bucket counts must be positive integers") + if (self.photo_only_temperatures is None) != (self.photo_only_counts is None): + raise ValueError("Photo-only temperatures and counts must be supplied together") + if self.photo_only_temperatures is not None: + if set(self.photo_only_temperatures) - set(self.temperatures) or set(self.photo_only_counts) != set(self.photo_only_temperatures): + raise ValueError("Photo-only buckets must name temperature buckets and match their counts") + for key, value in self.photo_only_temperatures.items(): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0: + raise ValueError("Invalid photo-only temperature artifact") + count = self.photo_only_counts[key] + if isinstance(count, bool) or not isinstance(count, int) or count < 1: + raise ValueError("Photo-only bucket counts must be positive integers") + + @classmethod + def fit(cls, rows: Iterable[Mapping[str, Any]], *, version: str | None = None, + unknown_offsets: bool = False) -> "TemperatureCalibrator": + grouped: dict[str, list[tuple[Sequence[float], int]]] = {} + for row in rows: + if row.get("partition") != "calibration": + raise ValueError("Only held-out calibration rows may fit temperatures") + option_count = row["option_count"] + if isinstance(option_count, bool) or not isinstance(option_count, int): + raise ValueError("option_count must be an integer") + if len(row["logits"]) != option_count + 1: + raise ValueError("option_count must equal len(logits) - 1 for unknown") + key = calibration_key(str(row["decision_type"]), option_count, EXTENDED_MAX_OPTIONS) + grouped.setdefault(key, []).append((row["logits"], row["target_index"])) + if not grouped: + raise ValueError("No calibration rows supplied") + offsets: dict[str, float] | None = None + if unknown_offsets: + fitted = {key: fit_unknown_offset_and_temperature(values) for key, values in sorted(grouped.items())} + offsets = {key: offset for key, (offset, _) in fitted.items()} + temperatures = {key: temperature for key, (_, temperature) in fitted.items()} + else: + temperatures = {key: fit_temperature(values) for key, values in sorted(grouped.items())} + counts = {key: len(values) for key, values in sorted(grouped.items())} + payload = {"temperatures": temperatures, "counts": counts, "unknown_offsets": offsets} + resolved_version = version or "temp-v1-" + hashlib.sha256( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest()[:12] + return cls(resolved_version, temperatures, counts, offsets) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> "TemperatureCalibrator": + if value.get("schema_version") not in ("1.0", "1.1", "1.2"): + raise ValueError("Unsupported calibration artifact schema") + offsets = value.get("unknown_offsets") + photo = value.get("photo_only_temperatures"); photo_counts = value.get("photo_only_counts") + return cls(str(value["calibration_version"]), dict(value["temperatures"]), dict(value["counts"]), + None if offsets is None else dict(offsets), + None if photo is None else dict(photo), None if photo_counts is None else dict(photo_counts)) + + @classmethod + def load(cls, path: str | Path) -> "TemperatureCalibrator": + return cls.from_dict(json.loads(Path(path).read_text())) + + def to_dict(self) -> dict[str, Any]: + schema = "1.2" if self.photo_only_temperatures is not None else ("1.1" if self.unknown_offsets is not None else "1.0") + payload = {"schema_version": schema, "calibration_version": self.version, + "temperatures": dict(self.temperatures), "counts": dict(self.counts)} + if self.unknown_offsets is not None: + payload["unknown_offsets"] = dict(self.unknown_offsets) + if self.photo_only_temperatures is not None: + payload["photo_only_temperatures"] = dict(self.photo_only_temperatures) + payload["photo_only_counts"] = dict(self.photo_only_counts) + return payload + + def temperature(self, decision_type: str, option_count: int, *, photo_only: bool = False) -> float | None: + """Bucket temperature; a photo-only request (images, empty state) uses its own bucket when the artifact has one.""" + key = calibration_key(decision_type, option_count, EXTENDED_MAX_OPTIONS) + if photo_only and self.photo_only_temperatures is not None and key in self.photo_only_temperatures: + return self.photo_only_temperatures[key] + return self.temperatures.get(key) + + def unknown_offset(self, decision_type: str, option_count: int, *, image: bool = False) -> float: + """Offset on the unknown logit for text-only requests; zero for requests with images or unseen buckets.""" + if image or not self.unknown_offsets: + return 0.0 + return float(self.unknown_offsets.get(calibration_key(decision_type, option_count, EXTENDED_MAX_OPTIONS), 0.0)) + + def calibrate_scores(self, raw_logits: Mapping[str, float], decision_type: str, + option_count: int, *, image: bool = False, photo_only: bool = False) -> tuple[dict[str, float], str | None]: + """Return identity softmax/None for an unseen bucket, including unknown safely.""" + if UNKNOWN not in raw_logits: + raise ValueError(f"Raw logits must include {UNKNOWN}") + if len(raw_logits) != option_count + 1: + raise ValueError("option_count must equal len(raw_logits) - 1 for unknown") + temperature = self.temperature(decision_type, option_count, photo_only=photo_only and image) + offset = self.unknown_offset(decision_type, option_count, image=image) + keys = list(raw_logits) + values = [raw_logits[key] + (offset if key == UNKNOWN else 0.0) for key in keys] + probabilities = softmax(values, temperature or 1.0) + return dict(zip(keys, probabilities)), self.version if temperature is not None else None + + def calibrate_result(self, result: Result, decision_type: str, option_count: int, *, image: bool = False, + photo_only: bool = False) -> Result: + """Rebuild a Result from calibrated logits; unknown participates like every other class. + + With a non-zero unknown offset (text-only requests) the argmax can move, so the value is re-derived + from the calibrated scores; otherwise the engine's selected value (with its tie break) is kept. + """ + scores, version = self.calibrate_scores(result.raw_logits, decision_type, option_count, image=image, photo_only=photo_only) + status, value, reason = result.status, result.value, result.reason + if self.unknown_offset(decision_type, option_count, image=image): + current = UNKNOWN if value is None else _score_key(value) + top = max(scores, key=lambda key: scores[key]) + if top != current and scores[top] > scores.get(current, float("-inf")): + if top == UNKNOWN: + status, value, reason = "abstained", None, "insufficient_evidence" + else: + status, value, reason = "answered", _typed_value(top, decision_type), None + return Result(status=status, value=value, + scores=scores, raw_logits=dict(result.raw_logits), + score_semantics="calibrated_normalized_scores" if version else "uncalibrated_normalized_scores", + calibration_version=version, + reason=reason) + + +def _score_key(value: Any) -> str: + """The scores/raw_logits key for a typed value (mirrors scoring.key).""" + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + +def _typed_value(key: str, decision_type: str) -> Any: + """Recover a typed value from a scores key when the offset moves the argmax.""" + if decision_type in ("boolean", "noul"): + if key not in ("true", "false"): + raise ValueError(f"Unexpected boolean key {key!r}") + return key == "true" + if decision_type in ("ordinal", "score"): + return int(key) + return key diff --git a/upstream/src/vision_decision/cli.py b/upstream/src/vision_decision/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..0233d0400f72d227fc6e1dc58ffabdfc15164547 --- /dev/null +++ b/upstream/src/vision_decision/cli.py @@ -0,0 +1,100 @@ +import argparse +import importlib.metadata +import json +from pathlib import Path +import platform +import subprocess +import sys +from .contracts import Request +from .images import load_image + +def hardware(): + info = {"architecture": platform.machine(), "os": platform.mac_ver()[0], "python": platform.python_version()} + if sys.platform == "darwin": + # Whitelist fields; never persist serial numbers or hardware UUIDs. + raw = subprocess.check_output(["system_profiler", "SPHardwareDataType", "-json"], text=True) + details = json.loads(raw)["SPHardwareDataType"][0] + info.update({k: details[k] for k in ("chip_type", "physical_memory", "machine_model") if k in details}) + info["packages"] = {} + for package in ("mlx", "mlx-vlm", "transformers", "Pillow", "pydantic"): + try: info["packages"][package] = importlib.metadata.version(package) + except importlib.metadata.PackageNotFoundError: pass + return info + +def calibrate_results(results, fields, path): + if path is None: + return results + from .calibration import TemperatureCalibrator + calibrator = TemperatureCalibrator.load(path) + return [calibrator.calibrate_result(result, field.type, len(result.scores) - 1) + for field, result in zip(fields, results)] + +def main(): + parser = argparse.ArgumentParser(prog="vd") + sub = parser.add_subparsers(dest="command", required=True) + hw = sub.add_parser("inspect-hardware") + hw.add_argument("--output") + val = sub.add_parser("validate-schema") + val.add_argument("--input", required=True) + pred = sub.add_parser("predict") + pred.add_argument("--image", help="optional image; omit for a text-only request") + pred.add_argument("--request", required=True) + pred.add_argument("--model-bundle", default="artifacts/model.json") + pred.add_argument("--rotations", type=int, default=4, help="candidate orders averaged per field") + pred.add_argument("--output") + dec = sub.add_parser("decide", help="Jev-style request: state + typed questions (noul / choice / score) with optional images") + dec.add_argument("--image", action="append", default=[], help="repeat for a reference/target pair (first = reference)") + dec.add_argument("--request", required=True) + dec.add_argument("--model-bundle", default="artifacts/model.json") + dec.add_argument("--adapter") + dec.add_argument("--rotations", type=int, default=1) + dec.add_argument("--output") + for command in (pred, dec): + command.add_argument("--calibration", help="held-out temperature calibration artifact") + args = parser.parse_args() + try: + if args.command == "inspect-hardware": + output = hardware() + elif args.command == "validate-schema": + request = Request.model_validate_json(Path(args.input).read_text()) + output = {"valid": True, "fields": len(request.fields), "mode": request.execution.mode} + elif args.command == "decide": + from .jev_api import to_request, to_response + request = to_request(json.loads(Path(args.request).read_text())) + if len(args.image) > 2: + raise ValueError("Provide at most two images") + loaded = [load_image(path) for path in args.image] + from .backend import MLXDirect + backend = MLXDirect(args.model_bundle, adapter=args.adapter) + images = [image for image, _ in loaded] + scored, run = backend.score_request(images[0] if len(images) == 1 else images, request.fields, request.state, args.rotations) + scored = calibrate_results(scored, request.fields, args.calibration) + run.pop("questions") + output = {**to_response(request, scored, model=backend.bundle["repo"] + ("+adapter" if args.adapter else "")), + "images": [meta for _, meta in loaded], "usage": run} + else: + request = Request.model_validate_json(Path(args.request).read_text()) + image, image_meta = load_image(args.image) if args.image else (None, None) + from .backend import MLXDirect + backend = MLXDirect(args.model_bundle) + scored, run = backend.score_request(image, request.fields, request.state, args.rotations) + scored = calibrate_results(scored, request.fields, args.calibration) + details = run.pop("questions") + results = {field.id: result.model_dump() for field, result in zip(request.fields, scored)} + timings = {field.id: detail for field, detail in zip(request.fields, details)} + output = {"schema_version": "1.0", "request_id": request.request_id, "results": results, + "model_bundle": {k: backend.bundle[k] for k in ("repo", "revision")}, "image": image_meta, + "execution": {"mode": "inspect", "automation_allowed": False, + "image_prefill_count": int(image is not None), "external_fallback_used": False, **run, + "model_load_seconds": backend.load_seconds, "fields": timings}} + text = json.dumps(output, indent=2, allow_nan=False) + "\n" + if getattr(args, "output", None): + Path(args.output).write_text(text) + else: print(text, end="") + except (ValueError, OSError, ImportError) as exc: + print(json.dumps({"error": type(exc).__name__, "message": str(exc)}), file=sys.stderr) + return 2 + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/upstream/src/vision_decision/contracts.py b/upstream/src/vision_decision/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..2656a42f3a34f96a2f7fcf646eba088fc6488e88 --- /dev/null +++ b/upstream/src/vision_decision/contracts.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import json +from typing import Annotated, Literal +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, model_validator + +# Serialized state limit (compact UTF-8 JSON). Raised from 32 KB to 128 KB in phase 3 (~32k tokens) so long documents can be +# trained and served; the processed-token limit (--max-input-tokens) remains the real guard. +MAX_STATE_BYTES = 131072 + +UNKNOWN = "__unknown__" +MAX_INTERNAL_FIELDS = 64 +Text = Annotated[StrictStr, Field(min_length=1, max_length=2000)] + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False) + +class Option(StrictModel): + value: Annotated[StrictStr, Field(min_length=1, max_length=128)] + description: Text | None = None # a bare label is a valid option, as in Jev's choice type + + @model_validator(mode="after") + def reserved(self): + if self.value == UNKNOWN: + raise ValueError("__unknown__ is reserved") + return self + +class Level(StrictModel): + value: StrictInt + description: Text + +class CommonField(StrictModel): + id: Annotated[StrictStr, Field(pattern=r"^[A-Za-z][A-Za-z0-9_]{0,63}$")] + question: Text + +class ChoiceField(CommonField): + type: Literal["choice"] + # +unknown: 254 options fill the shipped 255-code readout; 255 need the extended 256-code readout. + # The serving limit for the loaded adapter (254 or 255) is enforced by jev_api.to_request(max_options=...). + options: Annotated[list[Option], Field(min_length=2, max_length=255)] + + @model_validator(mode="after") + def unique(self): + if len({o.value for o in self.options}) != len(self.options): + raise ValueError("Choice values must be unique") + return self + +class BooleanField(CommonField): + type: Literal["boolean"] + # Optional criteria for each answer, as in Jev's noul type; the question may also be a statement. + yes_description: Text | None = None + no_description: Text | None = None + +class OrdinalField(CommonField): + type: Literal["ordinal"] + levels: Annotated[list[Level], Field(min_length=2, max_length=10)] # Jev's score type allows 2-10 levels + + @model_validator(mode="after") + def ordered(self): + values = [x.value for x in self.levels] + if values != sorted(set(values)): + raise ValueError("Ordinal levels must be unique and ascending") + return self + +DecisionField = Annotated[ChoiceField | BooleanField | OrdinalField, Field(discriminator="type")] + +class Execution(StrictModel): + mode: Literal["inspect"] = "inspect" + allow_external_fallback: Literal[False] = False + +class Request(StrictModel): + schema_version: Literal["1.0"] = "1.0" + request_id: Annotated[StrictStr, Field(min_length=1, max_length=128)] + state: dict | StrictStr = Field(default_factory=dict) + # A public request has at most 8 questions (jev_api.to_request); a `multi` question fans out to one + # boolean field per label, so the internal request may carry more fields. + fields: Annotated[list[DecisionField], Field(min_length=1, max_length=MAX_INTERNAL_FIELDS)] + execution: Execution = Field(default_factory=Execution) + + @model_validator(mode="after") + def bounds(self): + if len({f.id for f in self.fields}) != len(self.fields): + raise ValueError("Field IDs must be unique") + def check(value, depth=0): + if depth > 8: + raise ValueError("State nesting exceeds 8") + if isinstance(value, dict): + if not all(isinstance(k, str) for k in value): + raise ValueError("State keys must be strings") + for v in value.values(): check(v, depth + 1) + elif isinstance(value, list): + for v in value: check(v, depth + 1) + elif value is not None and type(value) not in (str, int, float, bool): + raise ValueError("State must contain JSON values") + check(self.state) + if len(json.dumps(self.state, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")) > MAX_STATE_BYTES: + raise ValueError(f"State exceeds {MAX_STATE_BYTES} bytes") + return self + +class Result(StrictModel): + status: Literal["answered", "abstained"] + value: StrictStr | StrictInt | bool | None + scores: dict[str, float] + raw_logits: dict[str, float] + score_semantics: Literal["uncalibrated_normalized_scores", "calibrated_normalized_scores"] = "uncalibrated_normalized_scores" + calibration_version: StrictStr | None = None + reason: Literal["insufficient_evidence"] | None = None + + @model_validator(mode="after") + def consistent(self): + import math + if (self.score_semantics == "calibrated_normalized_scores") != bool(self.calibration_version): + raise ValueError("Calibrated scores require a non-empty calibration version") + if not self.scores or set(self.scores) != set(self.raw_logits) or UNKNOWN not in self.scores: + raise ValueError("Score/logit keys must match and include unknown") + if not all(math.isfinite(v) and 0 <= v <= 1 for v in self.scores.values()): + raise ValueError("Invalid normalized scores") + if not all(math.isfinite(v) for v in self.raw_logits.values()): + raise ValueError("Invalid logits") + if not math.isclose(sum(self.scores.values()), 1.0, abs_tol=1e-6): + raise ValueError("Scores must sum to one") + if self.status == "abstained": + if self.value is not None or self.reason is None: + raise ValueError("Abstention requires null value and reason") + elif self.value is None or self.reason is not None: + raise ValueError("Answered result requires value and no reason") + return self diff --git a/upstream/src/vision_decision/gemma_backend.py b/upstream/src/vision_decision/gemma_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..66f20d89cb62a3fa2f52e861520142641dcf658e --- /dev/null +++ b/upstream/src/vision_decision/gemma_backend.py @@ -0,0 +1,40 @@ +"""Research-only Gemma 4 adapter; preserves the Qwen CLI backend.""" +import hashlib +from time import perf_counter +from .backend import MLXDirect +from .scoring import verified_label_ids, result_from_logits + +class GemmaDirect(MLXDirect): + def score_compiled(self,image,prompt,labels,choices): + from mlx_vlm.prompt_utils import apply_chat_template + from mlx_vlm.utils import prepare_inputs, should_add_special_tokens + mx=self.mx;start=perf_counter() + if self.model.config.model_type!='gemma4':raise ValueError('Expected Gemma 4') + images = [] if image is None else image if isinstance(image, list) else [image] + if len(images) > 2: raise ValueError('Supports at most two images') + rendered=apply_chat_template(self.processor,self.model.config,prompt,num_images=len(images),enable_thinking=False) + boundary='<|turn>model\n' + if not rendered.endswith(boundary):raise ValueError('Unverified Gemma answer boundary') + tokenizer=self.processor.tokenizer + token_ids=verified_label_ids(tokenizer,rendered,labels) + inputs=prepare_inputs(self.processor,images=images or None,prompts=rendered, + image_token_index=getattr(self.model.config,'image_token_index',None), + add_special_tokens=should_add_special_tokens(self.model.config.model_type,self.processor)) + ids=inputs.pop('input_ids');pixels=inputs.pop('pixel_values', None);mask=inputs.pop('attention_mask',None) + suffix=tokenizer.encode(boundary,add_special_tokens=False) + if ids[0,-len(suffix):].tolist()!=suffix:raise ValueError('Gemma processed suffix mismatch') + if ids.shape[0]!=1 or ids.shape[-1]>4096:raise ValueError('Unsupported sequence shape') + if mask is not None and not bool(mx.all(mask==1).item()):raise ValueError('Padding unsupported') + preprocess=perf_counter()-start;start=perf_counter() + # The processor mask is a 2-D padding mask, not a causal attention mask. + # With no padding, let Gemma construct its native sliding/full masks. + output=self.model(ids,pixels,mask=None,logits_to_keep=1,**inputs) + selected=output.logits[0,-1,mx.array(token_ids)].astype(mx.float32) + mx.eval(selected);logits=selected.tolist() + metadata=dict(preprocess_seconds=preprocess,forward_seconds=perf_counter()-start,input_tokens=ids.shape[-1], + choice_token_ids=token_ids,template_sha256=hashlib.sha256(rendered.encode()).hexdigest(),template_suffix=rendered[-64:], + peak_memory_bytes=mx.get_peak_memory(),logical_forward_evaluations=1, + image_grid_thw=None,image_count=len(images),pixel_values_shape=([list(x.shape) for x in pixels] if isinstance(pixels,list) else list(pixels.shape)) if pixels is not None else None, + visual_tokens=int(mx.sum(ids==self.model.config.image_token_id).item()), + tie_break_policy='lowest_vocabulary_token_id',attention_mask_policy='native causal masks; verified unpadded input') + return result_from_logits(choices,logits,token_ids=token_ids),metadata diff --git a/upstream/src/vision_decision/images.py b/upstream/src/vision_decision/images.py new file mode 100644 index 0000000000000000000000000000000000000000..2ffde5d25bc2f1fc984ee85713421fc2b259ccf7 --- /dev/null +++ b/upstream/src/vision_decision/images.py @@ -0,0 +1,31 @@ +import hashlib +import warnings +from pathlib import Path +from PIL import Image, ImageOps + +MAX_BYTES = 20 * 1024 * 1024 +MAX_PIXELS = 20_000_000 + +def load_image_bytes(data): + """Decode and validate one image already in memory (uploads, data URLs).""" + if len(data) > MAX_BYTES: + raise ValueError("Image exceeds 20 MiB") + from io import BytesIO + with warnings.catch_warnings(): + warnings.simplefilter("error", Image.DecompressionBombWarning) + with Image.open(BytesIO(data)) as source: + if source.format not in {"JPEG", "PNG", "WEBP"}: + raise ValueError("Only JPEG, PNG, and WebP are supported") + if getattr(source, "n_frames", 1) != 1: + raise ValueError("Multi-frame images are unsupported") + if source.width * source.height > MAX_PIXELS: + raise ValueError("Image exceeds 20 million decoded pixels") + source.load() + image = ImageOps.exif_transpose(source).convert("RGB") + return image, {"sha256": hashlib.sha256(data).hexdigest(), "width": image.width, "height": image.height, "bytes": len(data)} + +def load_image(path): + path = Path(path) + with path.open("rb") as handle: + data = handle.read(MAX_BYTES + 1) + return load_image_bytes(data) diff --git a/upstream/src/vision_decision/jev_api.py b/upstream/src/vision_decision/jev_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0f68bf666ccfd9d7b30a4c5206b3f59a1dccb7fd --- /dev/null +++ b/upstream/src/vision_decision/jev_api.py @@ -0,0 +1,174 @@ +"""Jev-style request and response shapes on top of the internal contract. + +Request: {"state": {...}, "questions": {"": {"type": "noul|choice|score", "instructions": "...", "criteria": ...}}} + instructions: a string, or an object such as {"question": "...", "today": "..."} (flattened to "key: value" lines); + backticks refer to state keys or dotted paths, e.g. `subject`, `listing.color` + noul criteria: optional {"true": "...", "false": "..."}; instructions may be a question or a statement + choice criteria: {"