Florence-2,小模型推進視覺任務的統(tǒng)一表征
共 10818字,需瀏覽 22分鐘
·
2024-07-23 07:00
微軟視覺基礎模型Florence-2開源了!
Florence-2是一種新穎的視覺基礎模型,具有統(tǒng)一的、基于提示的表示,可用于各種計算機視覺和視覺語言任務。雖然現(xiàn)有的VLM在遷移學習方面表現(xiàn)出色,但它們難以用簡單的指令執(zhí)行各種任務,這種能力意味著處理各種空間層次和語義粒度的復雜性。Florence-2 旨在將文本提示作為任務指令,并以文本形式生成理想的結果,無論是字幕、對象檢測、基礎還是分割。
但是,在各行各業(yè)的各種垂直領域任務,F(xiàn)lorence-2可能不支持,或者針對某項任務的輸出不符合預期。我們可以通過微調來優(yōu)化和改善Florence-2在垂直領域任務的效果。
Florence-2是一個sequence to sequence模型,使用 DaViT 視覺編碼器將圖像轉換為視覺Embedding,并使用 BERT 將prompt轉換為文本和位置Embedding。Florence-2主要優(yōu)勢在數(shù)據(jù)上,多任務學習設置需要大規(guī)模、高質量的注釋數(shù)據(jù)。為此,F(xiàn)lorence-2團隊開發(fā)了 FLD-5B,它包含 1.26 億張圖像上的 54 億條綜合視覺注釋,使用自動圖像注釋和模型細化的迭代策略。
模型鏈接:
模型推理:
import requestsfrom PIL import Imagefrom transformers import AutoProcessor, AutoModelForCausalLMfrom modelscope import snapshot_downloadmodel_dir = snapshot_download("AI-ModelScope/Florence-2-base")model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True)processor = AutoProcessor.from_pretrained(model_dir, trust_remote_code=True)prompt = "<OD>"url = "https://qinglite-1253448069.cos.ap-shanghai.myqcloud.com/web/31fc426c1575e80b6a4790e320e1f9bec9d7dfa6"image = Image.open(requests.get(url, stream=True).raw)inputs = processor(text=prompt, images=image, return_tensors="pt")generated_ids = model.generate(input_ids=inputs["input_ids"],pixel_values=inputs["pixel_values"],max_new_tokens=1024,do_sample=False,num_beams=3,)generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]parsed_answer = processor.post_process_generation(generated_text, task="<OD>", image_size=(image.width, image.height))print(parsed_answer)
我們介紹使用ms-swift對Florence-2-large-ft進行目標檢測任務的訓練, ms-swift是魔搭社區(qū)官方提供的LLM工具箱,支持250+大語言模型和35+多模態(tài)大模型的微調、推理、量化、評估和部署,包括:Qwen、Llama、GLM、Internlm、Yi、Baichuan、DeepSeek、Llava等系列模型。代碼開源地址:https://github.com/modelscope/swift
環(huán)境準備
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/git clone https://github.com/modelscope/swift.gitcd swiftpip install -e '.[llm]'
ms-swift已接入Florence-2系列模型,包括:Florence-2-base, Florence-2-base-ft, Florence-2-large, Florence-2-large-ft。這里我們以refcoco數(shù)據(jù)集為例, 訓練模型的目標檢測能力
數(shù)據(jù)集鏈接如下:
https://www.modelscope.cn/datasets/swift/refcoco/dataPeview
數(shù)據(jù)集處理邏輯
以給定目標輸出bounding box的目標檢測任務為例
Florence-2系列模型輸出的Bounding box 的格式為 <loc_{x1}><loc_{y1}><loc_{x2}><loc_{y2}>,其中 (x1, y1) 和 (x2, y2) 分別表示 bounding box 的左下角和右上角的坐標。這些坐標是相對于圖像尺寸進行歸一化的位置,每個方向被劃分為1000等分。
為了更好地持續(xù)學習, 我們在微調Florence時保留原模型的輸出格式, 具體表現(xiàn)為
對數(shù)據(jù)集中的boundingbox做了相應的轉換, 轉換邏輯可以用以下方法表示
def process_boundingbox(image, bbox):"""Process bounding box coordinates relative to the image dimensions.Args:image (PIL.Image): Image object.bbox (list): List of length four [x1, y1, x2, y2], representing the coordinates of the bounding box's bottom-left (x1, y1) and top-right (x2, y2) corners in pixel coordinates.Returns:list: A list containing a formatted string representing the processed bounding box. The string format is '<loc_x1><loc_y1><loc_x2><loc_y2>'."""width = image.widthheight = image.heightx1, y1, x2, y2 = [int(coord / dim * 999) for coord, dim in zip(bbox, [width, height, width, height])]return [f'<loc_{x1}><loc_{y1}><loc_{x2}><loc_{y2}>']
保留Florence-2模型針對特定任務的提示(prompt),例如輸出給定目標的bounding box任務,使用原模型的<OPEN_VOCABULARY_DETECTION>提示。將數(shù)據(jù)集中的模型輸入提示轉換為原模型支持的提示,轉換邏輯可以用以下方法表示:
def process_query(object):"""Process the query for the model to search for the target.Args:object (str): The target to be searched by the model.Returns:str: The model's input prompt formatted as "<OPEN_VOCABULARY_DETECTION>{object}"."""return f"<OPEN_VOCABULARY_DETECTION>{object}"
保留Florence-2模型的輸出格式, 例如輸出給定目標的bounding box任務, Florence模型以<目標><bbox>的格式輸出, 在處理數(shù)據(jù)集的過程中可以同樣保留這樣的格式
def process_response(object, processed_bbox):"""Combine the object and processed bounding box into a unified response.Args:object (str): The object or target related to the response.processed_bbox (str): The processed bounding box information.Returns:str: A unified response string combining the object and processed bounding box."""return object + processed_bbox
完整的數(shù)據(jù)集處理邏輯如下
from PIL import Imageimage_path = "/coco2014/train2014/COCO_train2014_000000009231.jpg"object = "top left suitcase"bbox = [3,8,380,284]image = Image.open(image_path)processed_bbox = process_boundingbox(image, bbox)query = process_query(object) # <OPEN_VOCABULARY_DETECTION>top left suitcaseresponse = process_response(object, processed_bbox) # top left suitcase<loc_4><loc_18><loc_593>,<loc_666>
ms-swift內置了數(shù)據(jù)集處理邏輯, 對于給定目標輸出bounding box的目標檢測任務, 你可以使用內置的refcoco-unofficial-grounding數(shù)據(jù)集。對于給定boundingbox輸出目標的目標檢測任務, 數(shù)據(jù)集處理邏輯類似。你可以使用內置的refcoco-unofficial-caption數(shù)據(jù)集。
你也可以使用自定義的本地數(shù)據(jù)集來訓練目標檢測任務, 格式如下
1. 對于給定bounding box詢問目標的任務, 在query中指定`<bbox>`, 在response中指定`<ref-object>`, 在`objects`提供目標和bounding box具體信息
2. 對于給定目標詢問bounding box的任務,在query中指定`<ref-object>`, 在response中指定`<bbox>`, 在`objects`提供目標和bounding box具體信息
```jsonl{"query": "Find <bbox>", "response": "<ref-object>", "images": ["/coco2014/train2014/COCO_train2014_000000001507.jpg"], "objects": "[[\"bottom right sandwich\", [331, 266, 612, 530]]]" }{"query": "Find <ref-object>", "response": "<bbox>", "images": ["/coco2014/train2014/COCO_train2014_000000001507.jpg"], "objects": "[[\"bottom right sandwich\", [331, 266, 612, 530]]]" }```
訓練時使用參數(shù)--dataset /path/to/local_dataset
目標檢測任務微調
以訓練2000份refcoco數(shù)據(jù)為例, 訓練Florence-2-large-ft模型的目標檢測能力
這里使用--lora_target_modules ALL來訓練整體模型的所有線性層, 你也可以通過指定--lora_target_modules Default來只訓練模型的qkv層減少顯存占用
# Experimental environment: 4090# 7GB GPU memoryCUDA_VISIBLE_DEVICES=0 swift sft \--model_type florence-2-large-ft \--dataset refcoco-unofficial-grounding#2000 \--lora_target_modules ALL# 2.3GB GPU memoryCUDA_VISIBLE_DEVICES=0 swift sft \--model_type florence-2-large-ft \--dataset refcoco-unofficial-grounding#2000 \--lora_target_modules DEFAULT
訓練損失可視化:
資源占用:
微調后模型的推理:
命令行推理
# Experimental environment: 4090CUDA_VISIBLE_DEVICES=0 swift infer \--ckpt_dir output/florence-2-large-ft/vx-xxx/checkpoint-xxx \--stream false \--max_new_tokens 1024
推理結果
<<< <OPEN_VOCABULARY_DETECTION>catInput a media path or URL <<< /coco2014/train2014/COCO_train2014_000000009231.jpg{'Locate cat in the image.': 'cat<loc_643><loc_290><loc_998><loc_773>'}--------------------------------------------------<<< <OPEN_VOCABULARY_DETECTION>dog laying closest to laptopInput a media path or URL <<< /coco2014/train2014/COCO_train2014_000000171435.jpg{'Locate dog laying closest to laptop in the image.': 'dog laying closest to laptop<loc_106><loc_449><loc_660>,<loc_627>'}
推理可視化
我們可以對模型輸出的 bounding box 進行可視化, 參考代碼如下
from PIL import Image, ImageDrawimport redef visualize_bounding_box(img, bbox):img_width, img_height = img.sizenumbers = re.findall(r'\d+', bbox)x1, y1, x2, y2 = [int(num) for num in numbers]x1 = int((x1 / 999) * img_width)y1 = int((y1 / 999) * img_height)x2 = int((x2 / 999) * img_width)y2 = int((y2 / 999) * img_height)draw = ImageDraw.Draw(img)# 繪制bounding boxdraw.rectangle([x1, y1, x2, y2], outline="red", width=2)img.show()# img.save("output_image.jpg")img_path = "/coco2014/train2014/COCO_train2014_000000171435.jpg"img = Image.open(img_path)bbox = '<loc_643><loc_290><loc_998><loc_773>'visualize_bounding_box(img, bbox)
可視化結果
{'Locate cat in the image.': 'cat<loc_643><loc_290><loc_998><loc_773>'}
{'Locate dog laying closest to laptop in the image.': 'dog laying closest to laptop<loc_106><loc_449><loc_660>,<loc_627>'}
點擊閱讀原文,即可跳轉模型頁~
