Upload fin-mm/code (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/qbench.sh +18 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/qbench_zh.sh +20 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/seed.sh +39 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/sqa.sh +16 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/textvqa.sh +13 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/vizwiz.sh +14 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/vqav2.sh +36 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune.sh +37 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_lora.sh +38 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_task.sh +36 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_task_lora.sh +37 -0
- fin-mm/code/LLaVA-Plus/scripts/v1_5/pretrain.sh +35 -0
- fin-mm/code/LLaVA-Plus/scripts/zero2.json +23 -0
- fin-mm/code/LLaVA-Plus/scripts/zero3.json +28 -0
- fin-mm/code/LLaVA-Plus/scripts/zero3_offload.json +56 -0
- fin-mm/code/LLaVA-Plus/serve/__init__.py +0 -0
- fin-mm/code/LLaVA-Plus/serve/blip2_test_message.py +108 -0
- fin-mm/code/LLaVA-Plus/serve/blip2_worker.py +369 -0
- fin-mm/code/LLaVA-Plus/serve/blip2grounding_test_message.py +124 -0
- fin-mm/code/LLaVA-Plus/serve/blip2grounding_worker.py +345 -0
- fin-mm/code/LLaVA-Plus/serve/clip_retrieval_test_message.py +125 -0
- fin-mm/code/LLaVA-Plus/serve/clip_retrieval_worker.py +384 -0
- fin-mm/code/LLaVA-Plus/serve/constants.py +58 -0
- fin-mm/code/LLaVA-Plus/serve/controller.py +303 -0
- fin-mm/code/LLaVA-Plus/serve/grounded_sam_test_message.py +155 -0
- fin-mm/code/LLaVA-Plus/serve/grounded_sam_worker.py +452 -0
- fin-mm/code/LLaVA-Plus/serve/grounding_dino_test_message.py +128 -0
- fin-mm/code/LLaVA-Plus/serve/grounding_dino_worker.py +358 -0
- fin-mm/code/LLaVA-Plus/serve/inpainting_message.py +187 -0
- fin-mm/code/LLaVA-Plus/serve/inpainting_worker.py +330 -0
- fin-mm/code/LLaVA-Plus/serve/instructpix2pix_test_message.py +115 -0
- fin-mm/code/LLaVA-Plus/serve/instructpix2pix_worker.py +330 -0
- fin-mm/code/LLaVA-Plus/serve/ocr_test_message.py +109 -0
- fin-mm/code/LLaVA-Plus/serve/ocr_worker.py +310 -0
- fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_test_message.py +123 -0
- fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_worker.py +490 -0
- fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_worker_readme.md +18 -0
- fin-mm/code/LLaVA-Plus/serve/ram_grounding_test_message.py +124 -0
- fin-mm/code/LLaVA-Plus/serve/ram_grounding_worker.py +346 -0
- fin-mm/code/LLaVA-Plus/serve/ram_test_message.py +109 -0
- fin-mm/code/LLaVA-Plus/serve/ram_worker.py +384 -0
- fin-mm/code/LLaVA-Plus/serve/sam_test_message.py +153 -0
- fin-mm/code/LLaVA-Plus/serve/sam_test_message_points.py +167 -0
- fin-mm/code/LLaVA-Plus/serve/sam_worker.py +425 -0
- fin-mm/code/LLaVA-Plus/serve/seem_test_message.py +113 -0
- fin-mm/code/LLaVA-Plus/serve/seem_worker.py +353 -0
- fin-mm/code/LLaVA-Plus/serve/semantic_sam_worker.py +308 -0
- fin-mm/code/LLaVA-Plus/serve/stablediffusion_test_message.py +104 -0
- fin-mm/code/LLaVA-Plus/serve/stablediffusion_worker.py +303 -0
- fin-mm/code/LLaVA-Plus/serve/utils.py +267 -0
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/qbench.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
if [ "$1" = "dev" ]; then
|
| 4 |
+
echo "Evaluating in 'dev' split."
|
| 5 |
+
elif [ "$1" = "test" ]; then
|
| 6 |
+
echo "Evaluating in 'test' split."
|
| 7 |
+
else
|
| 8 |
+
echo "Unknown split, please choose between 'dev' and 'test'."
|
| 9 |
+
exit 1
|
| 10 |
+
fi
|
| 11 |
+
|
| 12 |
+
python -m llava.eval.model_vqa_qbench \
|
| 13 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 14 |
+
--image-folder ./playground/data/eval/qbench/images_llvisionqa/ \
|
| 15 |
+
--questions-file ./playground/data/eval/qbench/llvisionqa_$1.json \
|
| 16 |
+
--answers-file ./playground/data/eval/qbench/llvisionqa_$1_answers.jsonl \
|
| 17 |
+
--conv-mode llava_v1 \
|
| 18 |
+
--lang en
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/qbench_zh.sh
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
if [ "$1" = "dev" ]; then
|
| 4 |
+
ZH_SPLIT="验证集"
|
| 5 |
+
echo "Evaluating in 'dev' split."
|
| 6 |
+
elif [ "$1" = "test" ]; then
|
| 7 |
+
ZH_SPLIT="测试集"
|
| 8 |
+
echo "Evaluating in 'test' split."
|
| 9 |
+
else
|
| 10 |
+
echo "Unknown split, please choose between 'dev' and 'test'."
|
| 11 |
+
exit 1
|
| 12 |
+
fi
|
| 13 |
+
|
| 14 |
+
python -m llava.eval.model_vqa_qbench \
|
| 15 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 16 |
+
--image-folder ./playground/data/eval/qbench/images_llvisionqa/ \
|
| 17 |
+
--questions-file ./playground/data/eval/qbench/质衡-问答-$ZH_SPLIT.json \
|
| 18 |
+
--answers-file ./playground/data/eval/qbench/llvisionqa_zh_$1_answers.jsonl \
|
| 19 |
+
--conv-mode llava_v1 \
|
| 20 |
+
--lang zh
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/seed.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
| 4 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
| 5 |
+
|
| 6 |
+
CHUNKS=${#GPULIST[@]}
|
| 7 |
+
|
| 8 |
+
CKPT="llava-v1.5-13b"
|
| 9 |
+
|
| 10 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
| 11 |
+
CUDA_VISIBLE_DEVICES=${GPULIST[$IDX]} python -m llava.eval.model_vqa_loader \
|
| 12 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 13 |
+
--question-file ./playground/data/eval/seed_bench/llava-seed-bench.jsonl \
|
| 14 |
+
--image-folder ./playground/data/eval/seed_bench \
|
| 15 |
+
--answers-file ./playground/data/eval/seed_bench/answers/$CKPT/${CHUNKS}_${IDX}.jsonl \
|
| 16 |
+
--num-chunks $CHUNKS \
|
| 17 |
+
--chunk-idx $IDX \
|
| 18 |
+
--temperature 0 \
|
| 19 |
+
--conv-mode vicuna_v1 &
|
| 20 |
+
done
|
| 21 |
+
|
| 22 |
+
wait
|
| 23 |
+
|
| 24 |
+
output_file=./playground/data/eval/seed_bench/answers/$CKPT/merge.jsonl
|
| 25 |
+
|
| 26 |
+
# Clear out the output file if it exists.
|
| 27 |
+
> "$output_file"
|
| 28 |
+
|
| 29 |
+
# Loop through the indices and concatenate each file.
|
| 30 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
| 31 |
+
cat ./playground/data/eval/seed_bench/answers/$CKPT/${CHUNKS}_${IDX}.jsonl >> "$output_file"
|
| 32 |
+
done
|
| 33 |
+
|
| 34 |
+
# Evaluate
|
| 35 |
+
python scripts/convert_seed_for_submission.py \
|
| 36 |
+
--annotation-file ./playground/data/eval/seed_bench/SEED-Bench.json \
|
| 37 |
+
--result-file $output_file \
|
| 38 |
+
--result-upload-file ./playground/data/eval/seed_bench/answers_upload/llava-v1.5-13b.jsonl
|
| 39 |
+
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/sqa.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
python -m llava.eval.model_vqa_science \
|
| 4 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 5 |
+
--question-file ./playground/data/eval/scienceqa/llava_test_CQM-A.json \
|
| 6 |
+
--image-folder ./playground/data/eval/scienceqa/images/test \
|
| 7 |
+
--answers-file ./playground/data/eval/scienceqa/answers/llava-v1.5-13b.jsonl \
|
| 8 |
+
--single-pred-prompt \
|
| 9 |
+
--temperature 0 \
|
| 10 |
+
--conv-mode vicuna_v1
|
| 11 |
+
|
| 12 |
+
python llava/eval/eval_science_qa.py \
|
| 13 |
+
--base-dir ./playground/data/eval/scienceqa \
|
| 14 |
+
--result-file ./playground/data/eval/scienceqa/answers/llava-v1.5-13b.jsonl \
|
| 15 |
+
--output-file ./playground/data/eval/scienceqa/answers/llava-v1.5-13b_output.jsonl \
|
| 16 |
+
--output-result ./playground/data/eval/scienceqa/answers/llava-v1.5-13b_result.json
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/textvqa.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
python -m llava.eval.model_vqa_loader \
|
| 4 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 5 |
+
--question-file ./playground/data/eval/textvqa/llava_textvqa_val_v051_ocr.jsonl \
|
| 6 |
+
--image-folder ./playground/data/eval/textvqa/train_images \
|
| 7 |
+
--answers-file ./playground/data/eval/textvqa/answers/llava-v1.5-13b.jsonl \
|
| 8 |
+
--temperature 0 \
|
| 9 |
+
--conv-mode vicuna_v1
|
| 10 |
+
|
| 11 |
+
python -m llava.eval.eval_textvqa \
|
| 12 |
+
--annotation-file ./playground/data/eval/textvqa/TextVQA_0.5.1_val.json \
|
| 13 |
+
--result-file ./playground/data/eval/textvqa/answers/llava-v1.5-13b.jsonl
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/vizwiz.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
python -m llava.eval.model_vqa_loader \
|
| 4 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 5 |
+
--question-file ./playground/data/eval/vizwiz/llava_test.jsonl \
|
| 6 |
+
--image-folder ./playground/data/eval/vizwiz/test \
|
| 7 |
+
--answers-file ./playground/data/eval/vizwiz/answers/llava-v1.5-13b.jsonl \
|
| 8 |
+
--temperature 0 \
|
| 9 |
+
--conv-mode vicuna_v1
|
| 10 |
+
|
| 11 |
+
python scripts/convert_vizwiz_for_submission.py \
|
| 12 |
+
--annotation-file ./playground/data/eval/vizwiz/llava_test.jsonl \
|
| 13 |
+
--result-file ./playground/data/eval/vizwiz/answers/llava-v1.5-13b.jsonl \
|
| 14 |
+
--result-upload-file ./playground/data/eval/vizwiz/answers_upload/llava-v1.5-13b.json
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/eval/vqav2.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
| 4 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
| 5 |
+
|
| 6 |
+
CHUNKS=${#GPULIST[@]}
|
| 7 |
+
|
| 8 |
+
CKPT="llava-v1.5-13b"
|
| 9 |
+
SPLIT="llava_vqav2_mscoco_test-dev2015"
|
| 10 |
+
|
| 11 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
| 12 |
+
CUDA_VISIBLE_DEVICES=${GPULIST[$IDX]} python -m llava.eval.model_vqa_loader \
|
| 13 |
+
--model-path liuhaotian/llava-v1.5-13b \
|
| 14 |
+
--question-file ./playground/data/eval/vqav2/$SPLIT.jsonl \
|
| 15 |
+
--image-folder ./playground/data/eval/vqav2/test2015 \
|
| 16 |
+
--answers-file ./playground/data/eval/vqav2/answers/$SPLIT/$CKPT/${CHUNKS}_${IDX}.jsonl \
|
| 17 |
+
--num-chunks $CHUNKS \
|
| 18 |
+
--chunk-idx $IDX \
|
| 19 |
+
--temperature 0 \
|
| 20 |
+
--conv-mode vicuna_v1 &
|
| 21 |
+
done
|
| 22 |
+
|
| 23 |
+
wait
|
| 24 |
+
|
| 25 |
+
output_file=./playground/data/eval/vqav2/answers/$SPLIT/$CKPT/merge.jsonl
|
| 26 |
+
|
| 27 |
+
# Clear out the output file if it exists.
|
| 28 |
+
> "$output_file"
|
| 29 |
+
|
| 30 |
+
# Loop through the indices and concatenate each file.
|
| 31 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
| 32 |
+
cat ./playground/data/eval/vqav2/answers/$SPLIT/$CKPT/${CHUNKS}_${IDX}.jsonl >> "$output_file"
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
python scripts/convert_vqav2_for_submission.py --split $SPLIT --ckpt $CKPT
|
| 36 |
+
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--deepspeed ./scripts/zero3.json \
|
| 5 |
+
--model_name_or_path lmsys/vicuna-13b-v1.5 \
|
| 6 |
+
--version v1 \
|
| 7 |
+
--data_path ./playground/data/llava_v1_5_mix665k.json \
|
| 8 |
+
--image_folder ./playground/data \
|
| 9 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 10 |
+
--pretrain_mm_mlp_adapter ./checkpoints/llava-v1.5-13b-pretrain/mm_projector.bin \
|
| 11 |
+
--mm_projector_type mlp2x_gelu \
|
| 12 |
+
--mm_vision_select_layer -2 \
|
| 13 |
+
--mm_use_im_start_end False \
|
| 14 |
+
--mm_use_im_patch_token False \
|
| 15 |
+
--image_aspect_ratio pad \
|
| 16 |
+
--group_by_modality_length True \
|
| 17 |
+
--bf16 True \
|
| 18 |
+
--output_dir ./checkpoints/llava-v1.5-13b \
|
| 19 |
+
--num_train_epochs 1 \
|
| 20 |
+
--per_device_train_batch_size 16 \
|
| 21 |
+
--per_device_eval_batch_size 4 \
|
| 22 |
+
--gradient_accumulation_steps 1 \
|
| 23 |
+
--evaluation_strategy "no" \
|
| 24 |
+
--save_strategy "steps" \
|
| 25 |
+
--save_steps 50000 \
|
| 26 |
+
--save_total_limit 1 \
|
| 27 |
+
--learning_rate 2e-5 \
|
| 28 |
+
--weight_decay 0. \
|
| 29 |
+
--warmup_ratio 0.03 \
|
| 30 |
+
--lr_scheduler_type "cosine" \
|
| 31 |
+
--logging_steps 1 \
|
| 32 |
+
--tf32 True \
|
| 33 |
+
--model_max_length 2048 \
|
| 34 |
+
--gradient_checkpointing True \
|
| 35 |
+
--dataloader_num_workers 4 \
|
| 36 |
+
--lazy_preprocess True \
|
| 37 |
+
--report_to wandb
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_lora.sh
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
|
| 5 |
+
--deepspeed ./scripts/zero3.json \
|
| 6 |
+
--model_name_or_path lmsys/vicuna-13b-v1.5 \
|
| 7 |
+
--version v1 \
|
| 8 |
+
--data_path ./playground/data/llava_v1_5_mix665k.json \
|
| 9 |
+
--image_folder ./playground/data \
|
| 10 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 11 |
+
--pretrain_mm_mlp_adapter ./checkpoints/llava-v1.5-13b-pretrain/mm_projector.bin \
|
| 12 |
+
--mm_projector_type mlp2x_gelu \
|
| 13 |
+
--mm_vision_select_layer -2 \
|
| 14 |
+
--mm_use_im_start_end False \
|
| 15 |
+
--mm_use_im_patch_token False \
|
| 16 |
+
--image_aspect_ratio pad \
|
| 17 |
+
--group_by_modality_length True \
|
| 18 |
+
--bf16 True \
|
| 19 |
+
--output_dir ./checkpoints/llava-v1.5-13b-lora \
|
| 20 |
+
--num_train_epochs 1 \
|
| 21 |
+
--per_device_train_batch_size 16 \
|
| 22 |
+
--per_device_eval_batch_size 4 \
|
| 23 |
+
--gradient_accumulation_steps 1 \
|
| 24 |
+
--evaluation_strategy "no" \
|
| 25 |
+
--save_strategy "steps" \
|
| 26 |
+
--save_steps 50000 \
|
| 27 |
+
--save_total_limit 1 \
|
| 28 |
+
--learning_rate 2e-4 \
|
| 29 |
+
--weight_decay 0. \
|
| 30 |
+
--warmup_ratio 0.03 \
|
| 31 |
+
--lr_scheduler_type "cosine" \
|
| 32 |
+
--logging_steps 1 \
|
| 33 |
+
--tf32 True \
|
| 34 |
+
--model_max_length 2048 \
|
| 35 |
+
--gradient_checkpointing True \
|
| 36 |
+
--dataloader_num_workers 4 \
|
| 37 |
+
--lazy_preprocess True \
|
| 38 |
+
--report_to wandb
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_task.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--deepspeed ./scripts/zero3.json \
|
| 5 |
+
--model_name_or_path liuhaotian/llava-v1.5-13b \
|
| 6 |
+
--version v1 \
|
| 7 |
+
--data_path ./playground/data/llava_v1_5_mix665k.json \
|
| 8 |
+
--image_folder ./playground/data \
|
| 9 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 10 |
+
--mm_projector_type mlp2x_gelu \
|
| 11 |
+
--mm_vision_select_layer -2 \
|
| 12 |
+
--mm_use_im_start_end False \
|
| 13 |
+
--mm_use_im_patch_token False \
|
| 14 |
+
--image_aspect_ratio pad \
|
| 15 |
+
--group_by_modality_length True \
|
| 16 |
+
--bf16 True \
|
| 17 |
+
--output_dir ./checkpoints/llava-v1.5-13b-task \
|
| 18 |
+
--num_train_epochs 1 \
|
| 19 |
+
--per_device_train_batch_size 16 \
|
| 20 |
+
--per_device_eval_batch_size 4 \
|
| 21 |
+
--gradient_accumulation_steps 1 \
|
| 22 |
+
--evaluation_strategy "no" \
|
| 23 |
+
--save_strategy "steps" \
|
| 24 |
+
--save_steps 50000 \
|
| 25 |
+
--save_total_limit 1 \
|
| 26 |
+
--learning_rate 2e-5 \
|
| 27 |
+
--weight_decay 0. \
|
| 28 |
+
--warmup_ratio 0.03 \
|
| 29 |
+
--lr_scheduler_type "cosine" \
|
| 30 |
+
--logging_steps 1 \
|
| 31 |
+
--tf32 True \
|
| 32 |
+
--model_max_length 2048 \
|
| 33 |
+
--gradient_checkpointing True \
|
| 34 |
+
--dataloader_num_workers 4 \
|
| 35 |
+
--lazy_preprocess True \
|
| 36 |
+
--report_to wandb
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/finetune_task_lora.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
|
| 5 |
+
--deepspeed ./scripts/zero3.json \
|
| 6 |
+
--model_name_or_path liuhaotian/llava-v1.5-13b \
|
| 7 |
+
--version v1 \
|
| 8 |
+
--data_path ./playground/data/llava_v1_5_mix665k.json \
|
| 9 |
+
--image_folder ./playground/data \
|
| 10 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 11 |
+
--mm_projector_type mlp2x_gelu \
|
| 12 |
+
--mm_vision_select_layer -2 \
|
| 13 |
+
--mm_use_im_start_end False \
|
| 14 |
+
--mm_use_im_patch_token False \
|
| 15 |
+
--image_aspect_ratio pad \
|
| 16 |
+
--group_by_modality_length True \
|
| 17 |
+
--bf16 True \
|
| 18 |
+
--output_dir ./checkpoints/llava-v1.5-13b-task-lora \
|
| 19 |
+
--num_train_epochs 1 \
|
| 20 |
+
--per_device_train_batch_size 16 \
|
| 21 |
+
--per_device_eval_batch_size 4 \
|
| 22 |
+
--gradient_accumulation_steps 1 \
|
| 23 |
+
--evaluation_strategy "no" \
|
| 24 |
+
--save_strategy "steps" \
|
| 25 |
+
--save_steps 50000 \
|
| 26 |
+
--save_total_limit 1 \
|
| 27 |
+
--learning_rate 2e-4 \
|
| 28 |
+
--weight_decay 0. \
|
| 29 |
+
--warmup_ratio 0.03 \
|
| 30 |
+
--lr_scheduler_type "cosine" \
|
| 31 |
+
--logging_steps 1 \
|
| 32 |
+
--tf32 True \
|
| 33 |
+
--model_max_length 2048 \
|
| 34 |
+
--gradient_checkpointing True \
|
| 35 |
+
--dataloader_num_workers 4 \
|
| 36 |
+
--lazy_preprocess True \
|
| 37 |
+
--report_to wandb
|
fin-mm/code/LLaVA-Plus/scripts/v1_5/pretrain.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
deepspeed llava/train/train_mem.py \
|
| 4 |
+
--deepspeed ./scripts/zero2.json \
|
| 5 |
+
--model_name_or_path lmsys/vicuna-13b-v1.5 \
|
| 6 |
+
--version plain \
|
| 7 |
+
--data_path ./playground/data/LLaVA-Pretrain/blip_laion_cc_sbu_558k.json \
|
| 8 |
+
--image_folder ./playground/data/LLaVA-Pretrain/images \
|
| 9 |
+
--vision_tower openai/clip-vit-large-patch14-336 \
|
| 10 |
+
--mm_projector_type mlp2x_gelu \
|
| 11 |
+
--tune_mm_mlp_adapter True \
|
| 12 |
+
--mm_vision_select_layer -2 \
|
| 13 |
+
--mm_use_im_start_end False \
|
| 14 |
+
--mm_use_im_patch_token False \
|
| 15 |
+
--bf16 True \
|
| 16 |
+
--output_dir ./checkpoints/llava-v1.5-13b-pretrain \
|
| 17 |
+
--num_train_epochs 1 \
|
| 18 |
+
--per_device_train_batch_size 32 \
|
| 19 |
+
--per_device_eval_batch_size 4 \
|
| 20 |
+
--gradient_accumulation_steps 1 \
|
| 21 |
+
--evaluation_strategy "no" \
|
| 22 |
+
--save_strategy "steps" \
|
| 23 |
+
--save_steps 24000 \
|
| 24 |
+
--save_total_limit 1 \
|
| 25 |
+
--learning_rate 1e-3 \
|
| 26 |
+
--weight_decay 0. \
|
| 27 |
+
--warmup_ratio 0.03 \
|
| 28 |
+
--lr_scheduler_type "cosine" \
|
| 29 |
+
--logging_steps 1 \
|
| 30 |
+
--tf32 True \
|
| 31 |
+
--model_max_length 2048 \
|
| 32 |
+
--gradient_checkpointing True \
|
| 33 |
+
--dataloader_num_workers 4 \
|
| 34 |
+
--lazy_preprocess True \
|
| 35 |
+
--report_to wandb
|
fin-mm/code/LLaVA-Plus/scripts/zero2.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fp16": {
|
| 3 |
+
"enabled": "auto",
|
| 4 |
+
"loss_scale": 0,
|
| 5 |
+
"loss_scale_window": 1000,
|
| 6 |
+
"initial_scale_power": 16,
|
| 7 |
+
"hysteresis": 2,
|
| 8 |
+
"min_loss_scale": 1
|
| 9 |
+
},
|
| 10 |
+
"bf16": {
|
| 11 |
+
"enabled": "auto"
|
| 12 |
+
},
|
| 13 |
+
"train_micro_batch_size_per_gpu": "auto",
|
| 14 |
+
"train_batch_size": "auto",
|
| 15 |
+
"gradient_accumulation_steps": "auto",
|
| 16 |
+
"zero_optimization": {
|
| 17 |
+
"stage": 2,
|
| 18 |
+
"overlap_comm": true,
|
| 19 |
+
"contiguous_gradients": true,
|
| 20 |
+
"sub_group_size": 1e9,
|
| 21 |
+
"reduce_bucket_size": "auto"
|
| 22 |
+
}
|
| 23 |
+
}
|
fin-mm/code/LLaVA-Plus/scripts/zero3.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fp16": {
|
| 3 |
+
"enabled": "auto",
|
| 4 |
+
"loss_scale": 0,
|
| 5 |
+
"loss_scale_window": 1000,
|
| 6 |
+
"initial_scale_power": 16,
|
| 7 |
+
"hysteresis": 2,
|
| 8 |
+
"min_loss_scale": 1
|
| 9 |
+
},
|
| 10 |
+
"bf16": {
|
| 11 |
+
"enabled": "auto"
|
| 12 |
+
},
|
| 13 |
+
"train_micro_batch_size_per_gpu": "auto",
|
| 14 |
+
"train_batch_size": "auto",
|
| 15 |
+
"gradient_accumulation_steps": "auto",
|
| 16 |
+
"zero_optimization": {
|
| 17 |
+
"stage": 3,
|
| 18 |
+
"overlap_comm": true,
|
| 19 |
+
"contiguous_gradients": true,
|
| 20 |
+
"sub_group_size": 1e9,
|
| 21 |
+
"reduce_bucket_size": "auto",
|
| 22 |
+
"stage3_prefetch_bucket_size": "auto",
|
| 23 |
+
"stage3_param_persistence_threshold": "auto",
|
| 24 |
+
"stage3_max_live_parameters": 1e9,
|
| 25 |
+
"stage3_max_reuse_distance": 1e9,
|
| 26 |
+
"stage3_gather_16bit_weights_on_model_save": true
|
| 27 |
+
}
|
| 28 |
+
}
|
fin-mm/code/LLaVA-Plus/scripts/zero3_offload.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fp16": {
|
| 3 |
+
"enabled": "auto",
|
| 4 |
+
"loss_scale": 0,
|
| 5 |
+
"loss_scale_window": 1000,
|
| 6 |
+
"initial_scale_power": 16,
|
| 7 |
+
"hysteresis": 2,
|
| 8 |
+
"min_loss_scale": 1
|
| 9 |
+
},
|
| 10 |
+
"bf16": {
|
| 11 |
+
"enabled": "auto"
|
| 12 |
+
},
|
| 13 |
+
"optimizer": {
|
| 14 |
+
"type": "AdamW",
|
| 15 |
+
"params": {
|
| 16 |
+
"lr": "auto",
|
| 17 |
+
"betas": "auto",
|
| 18 |
+
"eps": "auto",
|
| 19 |
+
"weight_decay": "auto"
|
| 20 |
+
}
|
| 21 |
+
},
|
| 22 |
+
"scheduler": {
|
| 23 |
+
"type": "WarmupLR",
|
| 24 |
+
"params": {
|
| 25 |
+
"warmup_min_lr": "auto",
|
| 26 |
+
"warmup_max_lr": "auto",
|
| 27 |
+
"warmup_num_steps": "auto"
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"zero_optimization": {
|
| 31 |
+
"stage": 3,
|
| 32 |
+
"offload_optimizer": {
|
| 33 |
+
"device": "cpu",
|
| 34 |
+
"pin_memory": true
|
| 35 |
+
},
|
| 36 |
+
"offload_param": {
|
| 37 |
+
"device": "cpu",
|
| 38 |
+
"pin_memory": true
|
| 39 |
+
},
|
| 40 |
+
"overlap_comm": true,
|
| 41 |
+
"contiguous_gradients": true,
|
| 42 |
+
"sub_group_size": 1e9,
|
| 43 |
+
"reduce_bucket_size": "auto",
|
| 44 |
+
"stage3_prefetch_bucket_size": "auto",
|
| 45 |
+
"stage3_param_persistence_threshold": "auto",
|
| 46 |
+
"stage3_max_live_parameters": 1e9,
|
| 47 |
+
"stage3_max_reuse_distance": 1e9,
|
| 48 |
+
"gather_16bit_weights_on_model_save": true
|
| 49 |
+
},
|
| 50 |
+
"gradient_accumulation_steps": "auto",
|
| 51 |
+
"gradient_clipping": "auto",
|
| 52 |
+
"train_batch_size": "auto",
|
| 53 |
+
"train_micro_batch_size_per_gpu": "auto",
|
| 54 |
+
"steps_per_print": 1e5,
|
| 55 |
+
"wall_clock_breakdown": false
|
| 56 |
+
}
|
fin-mm/code/LLaVA-Plus/serve/__init__.py
ADDED
|
File without changes
|
fin-mm/code/LLaVA-Plus/serve/blip2_test_message.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import base64
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torchvision.transforms.functional as F
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def encode(image: Image):
|
| 36 |
+
buffered = BytesIO()
|
| 37 |
+
image.save(buffered, format="JPEG")
|
| 38 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 39 |
+
return img_b64_str
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
model_name = args.model_name
|
| 44 |
+
|
| 45 |
+
if args.worker_address:
|
| 46 |
+
worker_addr = args.worker_address
|
| 47 |
+
else:
|
| 48 |
+
controller_addr = args.controller_address
|
| 49 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 50 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 51 |
+
models = ret.json()["models"]
|
| 52 |
+
models.sort()
|
| 53 |
+
print(f"Models: {models}")
|
| 54 |
+
|
| 55 |
+
ret = requests.post(
|
| 56 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 57 |
+
)
|
| 58 |
+
worker_addr = ret.json()["address"]
|
| 59 |
+
print(f"worker_addr: {worker_addr}")
|
| 60 |
+
|
| 61 |
+
if worker_addr == "":
|
| 62 |
+
print(f"No available workers for {model_name}")
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 66 |
+
if args.send_image:
|
| 67 |
+
img = load_image(args.image_path)
|
| 68 |
+
img_arg = encode(img)
|
| 69 |
+
else:
|
| 70 |
+
img_arg = args.image_path
|
| 71 |
+
datas = {
|
| 72 |
+
"model": model_name,
|
| 73 |
+
"image": img_arg,
|
| 74 |
+
}
|
| 75 |
+
tic = time.time()
|
| 76 |
+
response = requests.post(
|
| 77 |
+
worker_addr + "/worker_generate",
|
| 78 |
+
headers=headers,
|
| 79 |
+
json=datas,
|
| 80 |
+
)
|
| 81 |
+
toc = time.time()
|
| 82 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 83 |
+
|
| 84 |
+
print("detection result:")
|
| 85 |
+
print(response.json())
|
| 86 |
+
# response is 'Response' with :
|
| 87 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
# worker parameters
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 95 |
+
)
|
| 96 |
+
parser.add_argument("--worker-address", type=str)
|
| 97 |
+
parser.add_argument("--model-name", type=str, default='blip2')
|
| 98 |
+
|
| 99 |
+
# model parameters
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--image_path", type=str, default="assets/demo2.jpg"
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--send_image", action="store_true",
|
| 105 |
+
)
|
| 106 |
+
args = parser.parse_args()
|
| 107 |
+
|
| 108 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/blip2_worker.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import uvicorn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import requests
|
| 11 |
+
import numpy as np
|
| 12 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 13 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 14 |
+
import base64
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
import uuid
|
| 17 |
+
import threading
|
| 18 |
+
from typing import List, Tuple, Union
|
| 19 |
+
import time
|
| 20 |
+
import sys
|
| 21 |
+
import os
|
| 22 |
+
import json
|
| 23 |
+
import logging
|
| 24 |
+
import dataclasses
|
| 25 |
+
import asyncio
|
| 26 |
+
import argparse
|
| 27 |
+
import sys
|
| 28 |
+
import os
|
| 29 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 33 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from transformers import (
|
| 37 |
+
AutoTokenizer,
|
| 38 |
+
AutoModelForCausalLM,
|
| 39 |
+
LlamaTokenizer,
|
| 40 |
+
AutoModel,
|
| 41 |
+
)
|
| 42 |
+
except ImportError:
|
| 43 |
+
from transformers import (
|
| 44 |
+
AutoTokenizer,
|
| 45 |
+
AutoModelForCausalLM,
|
| 46 |
+
LLaMATokenizer,
|
| 47 |
+
AutoModel,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
GB = 1 << 30
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
now_file_name = os.__file__
|
| 55 |
+
logdir = "logs/workers/"
|
| 56 |
+
os.makedirs(logdir, exist_ok=True)
|
| 57 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 58 |
+
|
| 59 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 60 |
+
logger = build_logger(now_file_name, logfile)
|
| 61 |
+
global_counter = 0
|
| 62 |
+
|
| 63 |
+
model_semaphore = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def heart_beat_worker(controller):
|
| 67 |
+
while True:
|
| 68 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 69 |
+
controller.send_heart_beat()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ModelWorker:
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
controller_addr,
|
| 76 |
+
worker_addr,
|
| 77 |
+
worker_id,
|
| 78 |
+
no_register,
|
| 79 |
+
model_path,
|
| 80 |
+
model_names,
|
| 81 |
+
device,
|
| 82 |
+
):
|
| 83 |
+
self.controller_addr = controller_addr
|
| 84 |
+
self.worker_addr = worker_addr
|
| 85 |
+
self.worker_id = worker_id
|
| 86 |
+
if model_path.endswith("/"):
|
| 87 |
+
model_path = model_path[:-1]
|
| 88 |
+
self.model_names = model_names or [model_path.split("/")[-1]]
|
| 89 |
+
self.device = device
|
| 90 |
+
|
| 91 |
+
# load model
|
| 92 |
+
logger.info(
|
| 93 |
+
f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 94 |
+
self.processor = AutoProcessor.from_pretrained(model_path)
|
| 95 |
+
self.model = Blip2ForConditionalGeneration.from_pretrained(
|
| 96 |
+
model_path, torch_dtype=torch.float16)
|
| 97 |
+
self.model.eval()
|
| 98 |
+
self.model.to(device)
|
| 99 |
+
|
| 100 |
+
if not no_register:
|
| 101 |
+
self.register_to_controller()
|
| 102 |
+
self.heart_beat_thread = threading.Thread(
|
| 103 |
+
target=heart_beat_worker, args=(self,)
|
| 104 |
+
)
|
| 105 |
+
self.heart_beat_thread.start()
|
| 106 |
+
|
| 107 |
+
def register_to_controller(self):
|
| 108 |
+
logger.info("Register to controller")
|
| 109 |
+
|
| 110 |
+
url = self.controller_addr + "/register_worker"
|
| 111 |
+
data = {
|
| 112 |
+
"worker_name": self.worker_addr,
|
| 113 |
+
"check_heart_beat": True,
|
| 114 |
+
"worker_status": self.get_status(),
|
| 115 |
+
}
|
| 116 |
+
r = requests.post(url, json=data)
|
| 117 |
+
assert r.status_code == 200
|
| 118 |
+
|
| 119 |
+
def send_heart_beat(self):
|
| 120 |
+
logger.info(
|
| 121 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 122 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 123 |
+
f"global_counter: {global_counter}. "
|
| 124 |
+
f"worker_id: {worker_id}. "
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 128 |
+
|
| 129 |
+
while True:
|
| 130 |
+
try:
|
| 131 |
+
ret = requests.post(
|
| 132 |
+
url,
|
| 133 |
+
json={
|
| 134 |
+
"worker_name": self.worker_addr,
|
| 135 |
+
"queue_length": self.get_queue_length(),
|
| 136 |
+
},
|
| 137 |
+
timeout=5,
|
| 138 |
+
)
|
| 139 |
+
exist = ret.json()["exist"]
|
| 140 |
+
break
|
| 141 |
+
except requests.exceptions.RequestException as e:
|
| 142 |
+
logger.error(f"heart beat error: {e}")
|
| 143 |
+
time.sleep(5)
|
| 144 |
+
|
| 145 |
+
if not exist:
|
| 146 |
+
self.register_to_controller()
|
| 147 |
+
|
| 148 |
+
def get_queue_length(self):
|
| 149 |
+
if (
|
| 150 |
+
model_semaphore is None
|
| 151 |
+
or model_semaphore._value is None
|
| 152 |
+
or model_semaphore._waiters is None
|
| 153 |
+
):
|
| 154 |
+
return 0
|
| 155 |
+
else:
|
| 156 |
+
return (
|
| 157 |
+
args.limit_model_concurrency
|
| 158 |
+
- model_semaphore._value
|
| 159 |
+
+ len(model_semaphore._waiters)
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def get_status(self):
|
| 163 |
+
return {
|
| 164 |
+
"model_names": self.model_names,
|
| 165 |
+
"speed": 1,
|
| 166 |
+
"queue_length": self.get_queue_length(),
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 170 |
+
|
| 171 |
+
if os.path.exists(image_path):
|
| 172 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 173 |
+
else:
|
| 174 |
+
# base64 coding
|
| 175 |
+
image_source = Image.open(
|
| 176 |
+
BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 177 |
+
|
| 178 |
+
return image_source
|
| 179 |
+
|
| 180 |
+
def generate_stream_func(self, model, params, device):
|
| 181 |
+
# get inputs
|
| 182 |
+
image_path = params["image"]
|
| 183 |
+
|
| 184 |
+
# load image and run models
|
| 185 |
+
image = self.load_image(image_path)
|
| 186 |
+
|
| 187 |
+
# caption:
|
| 188 |
+
inputs = self.processor(image, return_tensors="pt").to(
|
| 189 |
+
device, torch.float16)
|
| 190 |
+
generated_ids = model.generate(**inputs, max_new_tokens=20)
|
| 191 |
+
generated_text = self.processor.batch_decode(
|
| 192 |
+
generated_ids, skip_special_tokens=True)[0].strip()
|
| 193 |
+
|
| 194 |
+
w, h = image.size
|
| 195 |
+
pred_dict = {
|
| 196 |
+
"caption": generated_text,
|
| 197 |
+
"size": [h, w], # H,W
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
return pred_dict
|
| 201 |
+
|
| 202 |
+
def generate_gate(self, params):
|
| 203 |
+
try:
|
| 204 |
+
|
| 205 |
+
ret = {"text": "", "error_code": 0}
|
| 206 |
+
ret = self.generate_stream_func(
|
| 207 |
+
self.model,
|
| 208 |
+
params,
|
| 209 |
+
self.device,
|
| 210 |
+
)
|
| 211 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 212 |
+
ret = {
|
| 213 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 214 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 215 |
+
}
|
| 216 |
+
except (ValueError, RuntimeError) as e:
|
| 217 |
+
ret = {
|
| 218 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 219 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 220 |
+
}
|
| 221 |
+
return ret
|
| 222 |
+
|
| 223 |
+
@torch.inference_mode()
|
| 224 |
+
def get_embeddings(self, params):
|
| 225 |
+
try:
|
| 226 |
+
tokenizer = self.tokenizer
|
| 227 |
+
is_llama = "llama" in str(
|
| 228 |
+
type(self.model)
|
| 229 |
+
) # vicuna support batch inference
|
| 230 |
+
is_chatglm = "chatglm" in str(type(self.model))
|
| 231 |
+
is_t5 = "t5" in str(type(self.model))
|
| 232 |
+
if is_llama:
|
| 233 |
+
encoding = tokenizer.batch_encode_plus(
|
| 234 |
+
params["input"], padding=True, return_tensors="pt"
|
| 235 |
+
)
|
| 236 |
+
input_ids = encoding["input_ids"].to(self.device)
|
| 237 |
+
attention_mask = encoding["attention_mask"].to(self.device)
|
| 238 |
+
model_output = self.model(
|
| 239 |
+
input_ids, attention_mask, output_hidden_states=True
|
| 240 |
+
)
|
| 241 |
+
data = model_output.hidden_states[-1]
|
| 242 |
+
mask = attention_mask.unsqueeze(-1).expand(data.size()).float()
|
| 243 |
+
masked_embeddings = data * mask
|
| 244 |
+
sum_embeddings = torch.sum(masked_embeddings, dim=1)
|
| 245 |
+
seq_length = torch.sum(mask, dim=1)
|
| 246 |
+
embedding = sum_embeddings / seq_length
|
| 247 |
+
normalized_embeddings = F.normalize(embedding, p=2, dim=1)
|
| 248 |
+
ret = {
|
| 249 |
+
"embedding": normalized_embeddings.tolist(),
|
| 250 |
+
"token_num": torch.sum(attention_mask).item(),
|
| 251 |
+
}
|
| 252 |
+
else:
|
| 253 |
+
embedding = []
|
| 254 |
+
token_num = 0
|
| 255 |
+
for text in params["input"]:
|
| 256 |
+
input_ids = tokenizer.encode(text, return_tensors="pt").to(
|
| 257 |
+
self.device
|
| 258 |
+
)
|
| 259 |
+
if is_t5:
|
| 260 |
+
model_output = self.model(
|
| 261 |
+
input_ids, decoder_input_ids=input_ids
|
| 262 |
+
)
|
| 263 |
+
else:
|
| 264 |
+
model_output = self.model(
|
| 265 |
+
input_ids, output_hidden_states=True)
|
| 266 |
+
if is_chatglm:
|
| 267 |
+
data = (
|
| 268 |
+
model_output.hidden_states[-1].transpose(0, 1))[0]
|
| 269 |
+
elif is_t5:
|
| 270 |
+
data = model_output.encoder_last_hidden_state[0]
|
| 271 |
+
else:
|
| 272 |
+
data = model_output.hidden_states[-1][0]
|
| 273 |
+
data = F.normalize(torch.mean(data, dim=0), p=2, dim=0)
|
| 274 |
+
embedding.append(data.tolist())
|
| 275 |
+
token_num += len(input_ids[0])
|
| 276 |
+
ret = {
|
| 277 |
+
"embedding": embedding,
|
| 278 |
+
"token_num": token_num,
|
| 279 |
+
}
|
| 280 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 281 |
+
ret = {
|
| 282 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 283 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 284 |
+
}
|
| 285 |
+
except (ValueError, RuntimeError) as e:
|
| 286 |
+
ret = {
|
| 287 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 288 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 289 |
+
}
|
| 290 |
+
return ret
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
app = FastAPI()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def release_model_semaphore():
|
| 297 |
+
model_semaphore.release()
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def acquire_model_semaphore():
|
| 301 |
+
global model_semaphore, global_counter
|
| 302 |
+
global_counter += 1
|
| 303 |
+
if model_semaphore is None:
|
| 304 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 305 |
+
return model_semaphore.acquire()
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def create_background_tasks():
|
| 309 |
+
background_tasks = BackgroundTasks()
|
| 310 |
+
background_tasks.add_task(release_model_semaphore)
|
| 311 |
+
return background_tasks
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@app.post("/worker_generate")
|
| 315 |
+
async def api_generate(request: Request):
|
| 316 |
+
params = await request.json()
|
| 317 |
+
await acquire_model_semaphore()
|
| 318 |
+
output = worker.generate_gate(params)
|
| 319 |
+
release_model_semaphore()
|
| 320 |
+
return JSONResponse(output)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@app.post("/worker_get_status")
|
| 324 |
+
async def api_get_status(request: Request):
|
| 325 |
+
return worker.get_status()
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@app.post("/model_details")
|
| 329 |
+
async def model_details(request: Request):
|
| 330 |
+
return {"context_length": worker.context_len}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
if __name__ == "__main__":
|
| 334 |
+
parser = argparse.ArgumentParser()
|
| 335 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 336 |
+
parser.add_argument("--port", type=int, default=21006)
|
| 337 |
+
parser.add_argument("--worker-address", type=str,
|
| 338 |
+
default="http://localhost:21006")
|
| 339 |
+
parser.add_argument(
|
| 340 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--model-path", type=str, default="Salesforce/blip2-opt-2.7b"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
parser.add_argument(
|
| 348 |
+
"--model-names",
|
| 349 |
+
default="blip2",
|
| 350 |
+
type=lambda s: s.split(","),
|
| 351 |
+
help="Optional display comma separated names",
|
| 352 |
+
)
|
| 353 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 354 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 355 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 356 |
+
parser.add_argument("--no-register", action="store_true")
|
| 357 |
+
args = parser.parse_args()
|
| 358 |
+
logger.info(f"args: {args}")
|
| 359 |
+
|
| 360 |
+
worker = ModelWorker(
|
| 361 |
+
args.controller_address,
|
| 362 |
+
args.worker_address,
|
| 363 |
+
worker_id,
|
| 364 |
+
args.no_register,
|
| 365 |
+
args.model_path,
|
| 366 |
+
args.model_names,
|
| 367 |
+
args.device,
|
| 368 |
+
)
|
| 369 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/blip2grounding_test_message.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
"box_threshold": args.box_threshold,
|
| 74 |
+
"text_threshold": args.text_threshold,
|
| 75 |
+
}
|
| 76 |
+
tic = time.time()
|
| 77 |
+
response = requests.post(
|
| 78 |
+
worker_addr + "/worker_generate",
|
| 79 |
+
headers=headers,
|
| 80 |
+
json=datas,
|
| 81 |
+
)
|
| 82 |
+
toc = time.time()
|
| 83 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 84 |
+
|
| 85 |
+
print("detection result:")
|
| 86 |
+
print(response.json())
|
| 87 |
+
# response is 'Response' with :
|
| 88 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# visualize
|
| 92 |
+
res = response.json()
|
| 93 |
+
boxes = torch.Tensor(res["boxes"])
|
| 94 |
+
logits = torch.Tensor(res["logits"])
|
| 95 |
+
phrases = res["phrases"]
|
| 96 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 97 |
+
annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 98 |
+
cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
parser = argparse.ArgumentParser()
|
| 102 |
+
# worker parameters
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument("--worker-address", type=str)
|
| 107 |
+
parser.add_argument("--model-name", type=str, default='blip2+grounding_dino')
|
| 108 |
+
|
| 109 |
+
# model parameters
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--box_threshold", type=float, default=0.3,
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--text_threshold", type=float, default=0.25,
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--send_image", action="store_true",
|
| 121 |
+
)
|
| 122 |
+
args = parser.parse_args()
|
| 123 |
+
|
| 124 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/blip2grounding_worker.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
from groundingdino.util import box_ops
|
| 6 |
+
|
| 7 |
+
from segment_anything import build_sam
|
| 8 |
+
from segment_anything.predictor import SamPredictor
|
| 9 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import asyncio
|
| 13 |
+
import dataclasses
|
| 14 |
+
import logging
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from typing import List, Tuple, Union
|
| 20 |
+
import threading
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
from io import BytesIO
|
| 24 |
+
import base64
|
| 25 |
+
|
| 26 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 27 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 28 |
+
import numpy as np
|
| 29 |
+
import requests
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 33 |
+
|
| 34 |
+
from groundingdino.util.inference import load_model, predict
|
| 35 |
+
import groundingdino.datasets.transforms as T
|
| 36 |
+
import pycocotools.mask as mask_util
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from transformers import (
|
| 41 |
+
AutoTokenizer,
|
| 42 |
+
AutoModelForCausalLM,
|
| 43 |
+
LlamaTokenizer,
|
| 44 |
+
AutoModel,
|
| 45 |
+
)
|
| 46 |
+
except ImportError:
|
| 47 |
+
from transformers import (
|
| 48 |
+
AutoTokenizer,
|
| 49 |
+
AutoModelForCausalLM,
|
| 50 |
+
LLaMATokenizer,
|
| 51 |
+
AutoModel,
|
| 52 |
+
)
|
| 53 |
+
import torch
|
| 54 |
+
import torch.nn.functional as F
|
| 55 |
+
import uvicorn
|
| 56 |
+
|
| 57 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 58 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 59 |
+
|
| 60 |
+
GB = 1 << 30
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
now_file_name = os.__file__
|
| 64 |
+
logdir = "logs/workers/"
|
| 65 |
+
os.makedirs(logdir, exist_ok=True)
|
| 66 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 67 |
+
|
| 68 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 69 |
+
logger = build_logger(now_file_name, logfile)
|
| 70 |
+
global_counter = 0
|
| 71 |
+
|
| 72 |
+
model_semaphore = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def heart_beat_worker(controller):
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 78 |
+
controller.send_heart_beat()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelWorker:
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
controller_addr,
|
| 85 |
+
worker_addr,
|
| 86 |
+
worker_id,
|
| 87 |
+
no_register,
|
| 88 |
+
grounding_dino_server,
|
| 89 |
+
blip2_server,
|
| 90 |
+
model_names,
|
| 91 |
+
device,
|
| 92 |
+
):
|
| 93 |
+
self.controller_addr = controller_addr
|
| 94 |
+
self.worker_addr = worker_addr
|
| 95 |
+
self.worker_id = worker_id
|
| 96 |
+
self.model_names = model_names
|
| 97 |
+
self.device = device
|
| 98 |
+
|
| 99 |
+
self.grounding_dino_server = grounding_dino_server
|
| 100 |
+
self.grounding_dino_server_addr = self.get_sub_worker_addr(grounding_dino_server)
|
| 101 |
+
print(f"grounding_dino_server_addr: {self.grounding_dino_server_addr}")
|
| 102 |
+
|
| 103 |
+
self.blip2_server = blip2_server
|
| 104 |
+
self.blip2_server_addr = self.get_sub_worker_addr(blip2_server)
|
| 105 |
+
print(f"blip2_server_addr: {self.blip2_server_addr}")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if not no_register:
|
| 109 |
+
self.register_to_controller()
|
| 110 |
+
self.heart_beat_thread = threading.Thread(
|
| 111 |
+
target=heart_beat_worker, args=(self,)
|
| 112 |
+
)
|
| 113 |
+
self.heart_beat_thread.start()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_sub_worker_addr(self, worker_name):
|
| 117 |
+
# get grounding dino addr
|
| 118 |
+
if worker_name.startswith("http"):
|
| 119 |
+
sub_server_addr = worker_name
|
| 120 |
+
else:
|
| 121 |
+
controller_addr = self.controller_addr
|
| 122 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 123 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 124 |
+
models = ret.json()["models"]
|
| 125 |
+
models.sort()
|
| 126 |
+
print(f"Models: {models}")
|
| 127 |
+
|
| 128 |
+
ret = requests.post(
|
| 129 |
+
controller_addr + "/get_worker_address", json={"model": worker_name}
|
| 130 |
+
)
|
| 131 |
+
sub_server_addr = ret.json()["address"]
|
| 132 |
+
# print(f"worker_name: {worker_name}")
|
| 133 |
+
return sub_server_addr
|
| 134 |
+
|
| 135 |
+
def register_to_controller(self):
|
| 136 |
+
logger.info("Register to controller")
|
| 137 |
+
|
| 138 |
+
url = self.controller_addr + "/register_worker"
|
| 139 |
+
data = {
|
| 140 |
+
"worker_name": self.worker_addr,
|
| 141 |
+
"check_heart_beat": True,
|
| 142 |
+
"worker_status": self.get_status(),
|
| 143 |
+
}
|
| 144 |
+
r = requests.post(url, json=data)
|
| 145 |
+
assert r.status_code == 200
|
| 146 |
+
|
| 147 |
+
def send_heart_beat(self):
|
| 148 |
+
logger.info(
|
| 149 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 150 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 151 |
+
f"global_counter: {global_counter}. "
|
| 152 |
+
f"worker_id: {worker_id}. "
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 156 |
+
|
| 157 |
+
while True:
|
| 158 |
+
try:
|
| 159 |
+
ret = requests.post(
|
| 160 |
+
url,
|
| 161 |
+
json={
|
| 162 |
+
"worker_name": self.worker_addr,
|
| 163 |
+
"queue_length": self.get_queue_length(),
|
| 164 |
+
},
|
| 165 |
+
timeout=5,
|
| 166 |
+
)
|
| 167 |
+
exist = ret.json()["exist"]
|
| 168 |
+
break
|
| 169 |
+
except requests.exceptions.RequestException as e:
|
| 170 |
+
logger.error(f"heart beat error: {e}")
|
| 171 |
+
time.sleep(5)
|
| 172 |
+
|
| 173 |
+
if not exist:
|
| 174 |
+
self.register_to_controller()
|
| 175 |
+
|
| 176 |
+
def get_queue_length(self):
|
| 177 |
+
if (
|
| 178 |
+
model_semaphore is None
|
| 179 |
+
or model_semaphore._value is None
|
| 180 |
+
or model_semaphore._waiters is None
|
| 181 |
+
):
|
| 182 |
+
return 0
|
| 183 |
+
else:
|
| 184 |
+
return (
|
| 185 |
+
args.limit_model_concurrency
|
| 186 |
+
- model_semaphore._value
|
| 187 |
+
+ len(model_semaphore._waiters)
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def get_status(self):
|
| 191 |
+
return {
|
| 192 |
+
"model_names": self.model_names,
|
| 193 |
+
"speed": 1,
|
| 194 |
+
"queue_length": self.get_queue_length(),
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if os.path.exists(image_path):
|
| 201 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 202 |
+
else:
|
| 203 |
+
# base64 coding
|
| 204 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 205 |
+
|
| 206 |
+
image = np.asarray(image_source)
|
| 207 |
+
image_transformed, _ = self.transform(image_source, None)
|
| 208 |
+
return image, image_transformed
|
| 209 |
+
|
| 210 |
+
def generate_stream_func(self, model, params, device):
|
| 211 |
+
# get inputs
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
headers = {"User-Agent": "G-SAM Client"}
|
| 216 |
+
|
| 217 |
+
# blip2
|
| 218 |
+
pred_dict_blip2 = requests.post(
|
| 219 |
+
self.blip2_server_addr + "/worker_generate",
|
| 220 |
+
headers=headers,
|
| 221 |
+
json=params,
|
| 222 |
+
).json()
|
| 223 |
+
|
| 224 |
+
params.update({
|
| 225 |
+
"caption": pred_dict_blip2["caption"],
|
| 226 |
+
})
|
| 227 |
+
|
| 228 |
+
# gdino
|
| 229 |
+
pred_dict_gdino = requests.post(
|
| 230 |
+
self.grounding_dino_server_addr + "/worker_generate",
|
| 231 |
+
headers=headers,
|
| 232 |
+
json=params,
|
| 233 |
+
).json()
|
| 234 |
+
|
| 235 |
+
pred_dict_gdino.update({
|
| 236 |
+
"caption": pred_dict_blip2["caption"],
|
| 237 |
+
})
|
| 238 |
+
|
| 239 |
+
return pred_dict_gdino
|
| 240 |
+
|
| 241 |
+
def generate_gate(self, params):
|
| 242 |
+
try:
|
| 243 |
+
|
| 244 |
+
ret = {"text": "", "error_code": 0}
|
| 245 |
+
ret = self.generate_stream_func(
|
| 246 |
+
None,
|
| 247 |
+
params,
|
| 248 |
+
self.device,
|
| 249 |
+
)
|
| 250 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 251 |
+
ret = {
|
| 252 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 253 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 254 |
+
}
|
| 255 |
+
except (ValueError, RuntimeError) as e:
|
| 256 |
+
ret = {
|
| 257 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 258 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 259 |
+
}
|
| 260 |
+
return ret
|
| 261 |
+
|
| 262 |
+
app = FastAPI()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def release_model_semaphore():
|
| 266 |
+
model_semaphore.release()
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def acquire_model_semaphore():
|
| 270 |
+
global model_semaphore, global_counter
|
| 271 |
+
global_counter += 1
|
| 272 |
+
if model_semaphore is None:
|
| 273 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 274 |
+
return model_semaphore.acquire()
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def create_background_tasks():
|
| 278 |
+
background_tasks = BackgroundTasks()
|
| 279 |
+
background_tasks.add_task(release_model_semaphore)
|
| 280 |
+
return background_tasks
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@app.post("/worker_generate")
|
| 285 |
+
async def api_generate(request: Request):
|
| 286 |
+
params = await request.json()
|
| 287 |
+
await acquire_model_semaphore()
|
| 288 |
+
output = worker.generate_gate(params)
|
| 289 |
+
release_model_semaphore()
|
| 290 |
+
return JSONResponse(output)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@app.post("/worker_get_status")
|
| 294 |
+
async def api_get_status(request: Request):
|
| 295 |
+
return worker.get_status()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@app.post("/model_details")
|
| 302 |
+
async def model_details(request: Request):
|
| 303 |
+
return {"context_length": worker.context_len}
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
parser = argparse.ArgumentParser()
|
| 308 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 309 |
+
parser.add_argument("--port", type=int, default=21078)
|
| 310 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21078")
|
| 311 |
+
parser.add_argument(
|
| 312 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
parser.add_argument(
|
| 316 |
+
"--grounding-dino-server", type=str, default="grounding_dino"
|
| 317 |
+
)
|
| 318 |
+
parser.add_argument(
|
| 319 |
+
"--blip2-server", type=str, default="blip2"
|
| 320 |
+
)
|
| 321 |
+
parser.add_argument(
|
| 322 |
+
"--model-names",
|
| 323 |
+
default="blip2+grounding_dino",
|
| 324 |
+
type=lambda s: s.split(","),
|
| 325 |
+
help="Optional display comma separated names",
|
| 326 |
+
)
|
| 327 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 328 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 329 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 330 |
+
parser.add_argument("--no-register", action="store_true")
|
| 331 |
+
args = parser.parse_args()
|
| 332 |
+
logger.info(f"args: {args}")
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
worker = ModelWorker(
|
| 336 |
+
args.controller_address,
|
| 337 |
+
args.worker_address,
|
| 338 |
+
worker_id,
|
| 339 |
+
args.no_register,
|
| 340 |
+
args.grounding_dino_server,
|
| 341 |
+
args.blip2_server,
|
| 342 |
+
args.model_names,
|
| 343 |
+
args.device,
|
| 344 |
+
)
|
| 345 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/clip_retrieval_test_message.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
"box_threshold": args.box_threshold,
|
| 74 |
+
"text_threshold": args.text_threshold,
|
| 75 |
+
}
|
| 76 |
+
tic = time.time()
|
| 77 |
+
response = requests.post(
|
| 78 |
+
worker_addr + "/worker_generate",
|
| 79 |
+
headers=headers,
|
| 80 |
+
json=datas,
|
| 81 |
+
)
|
| 82 |
+
toc = time.time()
|
| 83 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 84 |
+
|
| 85 |
+
print("detection result:")
|
| 86 |
+
print(response.json())
|
| 87 |
+
# import ipdb; ipdb.set_trace()
|
| 88 |
+
# response is 'Response' with :
|
| 89 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# # visualize
|
| 93 |
+
# res = response.json()
|
| 94 |
+
# boxes = torch.Tensor(res["boxes"])
|
| 95 |
+
# logits = torch.Tensor(res["logits"])
|
| 96 |
+
# phrases = res["phrases"]
|
| 97 |
+
# image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 98 |
+
# annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 99 |
+
# cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
parser = argparse.ArgumentParser()
|
| 103 |
+
# worker parameters
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument("--worker-address", type=str)
|
| 108 |
+
parser.add_argument("--model-name", type=str, default='clip')
|
| 109 |
+
|
| 110 |
+
# model parameters
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--image_path", type=str, default="assets/demo2.jpg"
|
| 113 |
+
)
|
| 114 |
+
parser.add_argument(
|
| 115 |
+
"--box_threshold", type=float, default=0.3,
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--text_threshold", type=float, default=0.25,
|
| 119 |
+
)
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--send_image", action="store_true",
|
| 122 |
+
)
|
| 123 |
+
args = parser.parse_args()
|
| 124 |
+
|
| 125 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/clip_retrieval_worker.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
Using
|
| 4 |
+
"""
|
| 5 |
+
import sys, os
|
| 6 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import asyncio
|
| 10 |
+
import dataclasses
|
| 11 |
+
import logging
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
from typing import List, Tuple, Union
|
| 17 |
+
import threading
|
| 18 |
+
import uuid
|
| 19 |
+
|
| 20 |
+
from io import BytesIO
|
| 21 |
+
import base64
|
| 22 |
+
|
| 23 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 24 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 25 |
+
import numpy as np
|
| 26 |
+
import requests
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
from clip_retrieval.clip_client import ClipClient, Modality
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn.functional as F
|
| 34 |
+
import uvicorn
|
| 35 |
+
import clip # pylint: disable=import-outside-toplevel
|
| 36 |
+
|
| 37 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 38 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 39 |
+
|
| 40 |
+
from PIL import Image as pimage
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
GB = 1 << 30
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
now_file_name = os.__file__
|
| 47 |
+
logdir = "logs/workers/"
|
| 48 |
+
os.makedirs(logdir, exist_ok=True)
|
| 49 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 50 |
+
|
| 51 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 52 |
+
logger = build_logger(now_file_name, logfile)
|
| 53 |
+
global_counter = 0
|
| 54 |
+
|
| 55 |
+
model_semaphore = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def heart_beat_worker(controller):
|
| 59 |
+
while True:
|
| 60 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 61 |
+
controller.send_heart_beat()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ModelWorker:
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
controller_addr,
|
| 70 |
+
worker_addr,
|
| 71 |
+
worker_id,
|
| 72 |
+
no_register,
|
| 73 |
+
model_path,
|
| 74 |
+
model_names,
|
| 75 |
+
device,
|
| 76 |
+
indice_name,
|
| 77 |
+
):
|
| 78 |
+
self.controller_addr = controller_addr
|
| 79 |
+
self.worker_addr = worker_addr
|
| 80 |
+
self.worker_id = worker_id
|
| 81 |
+
self.model_names = model_names
|
| 82 |
+
self.device = device
|
| 83 |
+
|
| 84 |
+
# load clip
|
| 85 |
+
logger.info(f"Loading clip ...")
|
| 86 |
+
self.model, self.preprocess = clip.load("ViT-L/14", device=device, jit=True)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# load model
|
| 90 |
+
logger.info(f"Loading client ...")
|
| 91 |
+
self.client = ClipClient(
|
| 92 |
+
url="https://knn.laion.ai/knn-service",
|
| 93 |
+
indice_name=indice_name,
|
| 94 |
+
aesthetic_score=9,
|
| 95 |
+
aesthetic_weight=0.5,
|
| 96 |
+
modality=Modality.IMAGE,
|
| 97 |
+
num_images=20,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if indice_name == "laion5B-H-14":
|
| 101 |
+
os.environ['SEND_IMAGE'] = "True"
|
| 102 |
+
print("Set SEND_IMAGE to True, since indice_name is laion5B-H-14")
|
| 103 |
+
print("SEND_IMAGE", os.getenv("SEND_IMAGE", False))
|
| 104 |
+
|
| 105 |
+
if not no_register:
|
| 106 |
+
self.register_to_controller()
|
| 107 |
+
self.heart_beat_thread = threading.Thread(
|
| 108 |
+
target=heart_beat_worker, args=(self,)
|
| 109 |
+
)
|
| 110 |
+
self.heart_beat_thread.start()
|
| 111 |
+
|
| 112 |
+
def normalized(self, a, axis=-1, order=2):
|
| 113 |
+
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
|
| 114 |
+
l2[l2 == 0] = 1
|
| 115 |
+
return a / np.expand_dims(l2, axis)
|
| 116 |
+
|
| 117 |
+
def get_text_emb(self, text):
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
text_emb = self.model.encode_text(clip.tokenize([text], truncate=True).to(self.device))
|
| 120 |
+
text_emb /= text_emb.norm(dim=-1, keepdim=True)
|
| 121 |
+
text_emb = text_emb.cpu().detach().numpy().astype("float32")[0]
|
| 122 |
+
return text_emb
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_image_emb(self, image):
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
image_emb = self.model.encode_image(self.preprocess(image).unsqueeze(0).to(self.device))
|
| 128 |
+
image_emb /= image_emb.norm(dim=-1, keepdim=True)
|
| 129 |
+
image_emb = image_emb.cpu().detach().numpy().astype("float32")[0]
|
| 130 |
+
return image_emb
|
| 131 |
+
|
| 132 |
+
def register_to_controller(self):
|
| 133 |
+
logger.info("Register to controller")
|
| 134 |
+
|
| 135 |
+
url = self.controller_addr + "/register_worker"
|
| 136 |
+
data = {
|
| 137 |
+
"worker_name": self.worker_addr,
|
| 138 |
+
"check_heart_beat": True,
|
| 139 |
+
"worker_status": self.get_status(),
|
| 140 |
+
}
|
| 141 |
+
r = requests.post(url, json=data)
|
| 142 |
+
assert r.status_code == 200
|
| 143 |
+
|
| 144 |
+
def send_heart_beat(self):
|
| 145 |
+
logger.info(
|
| 146 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 147 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 148 |
+
f"global_counter: {global_counter}. "
|
| 149 |
+
f"worker_id: {worker_id}. "
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 153 |
+
|
| 154 |
+
while True:
|
| 155 |
+
try:
|
| 156 |
+
ret = requests.post(
|
| 157 |
+
url,
|
| 158 |
+
json={
|
| 159 |
+
"worker_name": self.worker_addr,
|
| 160 |
+
"queue_length": self.get_queue_length(),
|
| 161 |
+
},
|
| 162 |
+
timeout=5,
|
| 163 |
+
)
|
| 164 |
+
exist = ret.json()["exist"]
|
| 165 |
+
break
|
| 166 |
+
except requests.exceptions.RequestException as e:
|
| 167 |
+
logger.error(f"heart beat error: {e}")
|
| 168 |
+
time.sleep(5)
|
| 169 |
+
|
| 170 |
+
if not exist:
|
| 171 |
+
self.register_to_controller()
|
| 172 |
+
|
| 173 |
+
def get_queue_length(self):
|
| 174 |
+
if (
|
| 175 |
+
model_semaphore is None
|
| 176 |
+
or model_semaphore._value is None
|
| 177 |
+
or model_semaphore._waiters is None
|
| 178 |
+
):
|
| 179 |
+
return 0
|
| 180 |
+
else:
|
| 181 |
+
return (
|
| 182 |
+
args.limit_model_concurrency
|
| 183 |
+
- model_semaphore._value
|
| 184 |
+
+ len(model_semaphore._waiters)
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def get_status(self):
|
| 188 |
+
return {
|
| 189 |
+
"model_names": self.model_names,
|
| 190 |
+
"speed": 1,
|
| 191 |
+
"queue_length": self.get_queue_length(),
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
def load_image(self, image_path: str) -> Image.Image:
|
| 195 |
+
|
| 196 |
+
if os.path.exists(image_path):
|
| 197 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 198 |
+
else:
|
| 199 |
+
# base64 coding
|
| 200 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 201 |
+
|
| 202 |
+
return image_source
|
| 203 |
+
|
| 204 |
+
def generate_stream_func(self, model, params, device):
|
| 205 |
+
# get inputs
|
| 206 |
+
image_path = params["image"]
|
| 207 |
+
# load image and run models
|
| 208 |
+
image = self.load_image(image_path)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
if not os.getenv("SEND_IMAGE", False):
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# embedding
|
| 215 |
+
tic = time.time()
|
| 216 |
+
image_emb = self.get_image_emb(image)
|
| 217 |
+
embed_time = time.time() - tic
|
| 218 |
+
|
| 219 |
+
# search
|
| 220 |
+
tic = time.time()
|
| 221 |
+
beach_results = self.client.query(embedding_input=image_emb.tolist())
|
| 222 |
+
query_time = time.time() - tic
|
| 223 |
+
|
| 224 |
+
print("embed_time", embed_time, "query_time", query_time)
|
| 225 |
+
print(beach_results)
|
| 226 |
+
else:
|
| 227 |
+
# save image
|
| 228 |
+
save_name = "test.jpg"
|
| 229 |
+
image.save(save_name)
|
| 230 |
+
beach_results = self.client.query(image=save_name)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
w, h = image.size
|
| 234 |
+
pred_dict = {
|
| 235 |
+
"retrieval_results": beach_results,
|
| 236 |
+
"size": [h, w], # H,W
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
return pred_dict
|
| 240 |
+
|
| 241 |
+
def generate_gate(self, params):
|
| 242 |
+
try:
|
| 243 |
+
|
| 244 |
+
ret = {"text": "", "error_code": 0}
|
| 245 |
+
ret = self.generate_stream_func(
|
| 246 |
+
None,
|
| 247 |
+
params,
|
| 248 |
+
self.device,
|
| 249 |
+
)
|
| 250 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 251 |
+
ret = {
|
| 252 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 253 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 254 |
+
}
|
| 255 |
+
except (ValueError, RuntimeError) as e:
|
| 256 |
+
ret = {
|
| 257 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 258 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 259 |
+
}
|
| 260 |
+
return ret
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# app = FastAPI()
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# def release_model_semaphore():
|
| 268 |
+
# model_semaphore.release()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# def acquire_model_semaphore():
|
| 272 |
+
# global model_semaphore, global_counter
|
| 273 |
+
# global_counter += 1
|
| 274 |
+
# if model_semaphore is None:
|
| 275 |
+
# model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 276 |
+
# return model_semaphore.acquire()
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# def create_background_tasks():
|
| 280 |
+
# background_tasks = BackgroundTasks()
|
| 281 |
+
# background_tasks.add_task(release_model_semaphore)
|
| 282 |
+
# return background_tasks
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# @app.post("/worker_generate")
|
| 287 |
+
# async def api_generate(request: Request):
|
| 288 |
+
# params = await request.json()
|
| 289 |
+
# await acquire_model_semaphore()
|
| 290 |
+
# output = worker.generate_gate(params)
|
| 291 |
+
# release_model_semaphore()
|
| 292 |
+
# return JSONResponse(output)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# @app.post("/worker_get_status")
|
| 296 |
+
# async def api_get_status(request: Request):
|
| 297 |
+
# return worker.get_status()
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# @app.post("/model_details")
|
| 304 |
+
# async def model_details(request: Request):
|
| 305 |
+
# return {"context_length": worker.context_len}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
app = FastAPI()
|
| 310 |
+
def release_model_semaphore():
|
| 311 |
+
model_semaphore.release()
|
| 312 |
+
|
| 313 |
+
def acquire_model_semaphore():
|
| 314 |
+
global model_semaphore, global_counter
|
| 315 |
+
global_counter += 1
|
| 316 |
+
if model_semaphore is None:
|
| 317 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 318 |
+
return model_semaphore.acquire()
|
| 319 |
+
|
| 320 |
+
def create_background_tasks():
|
| 321 |
+
background_tasks = BackgroundTasks()
|
| 322 |
+
background_tasks.add_task(release_model_semaphore)
|
| 323 |
+
return background_tasks
|
| 324 |
+
|
| 325 |
+
@app.post("/worker_generate")
|
| 326 |
+
async def api_generate(request: Request):
|
| 327 |
+
params = await request.json()
|
| 328 |
+
await acquire_model_semaphore()
|
| 329 |
+
output = worker.generate_gate(params)
|
| 330 |
+
release_model_semaphore()
|
| 331 |
+
return JSONResponse(output)
|
| 332 |
+
|
| 333 |
+
@app.post("/worker_get_status")
|
| 334 |
+
async def api_get_status(request: Request):
|
| 335 |
+
return worker.get_status()
|
| 336 |
+
|
| 337 |
+
@app.post("/model_details")
|
| 338 |
+
async def model_details(request: Request):
|
| 339 |
+
return {"context_length": worker.context_len}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
parser = argparse.ArgumentParser()
|
| 343 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 344 |
+
parser.add_argument("--port", type=int, default=21046)
|
| 345 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21046")
|
| 346 |
+
parser.add_argument(
|
| 347 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
parser.add_argument(
|
| 351 |
+
"--model-path", type=str, default="Salesforce/blip2-opt-2.7b"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
parser.add_argument(
|
| 355 |
+
"--model-names",
|
| 356 |
+
default="retrieval,clip",
|
| 357 |
+
type=lambda s: s.split(","),
|
| 358 |
+
help="Optional display comma separated names",
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
parser.add_argument(
|
| 362 |
+
"--indice_name",
|
| 363 |
+
type=str,
|
| 364 |
+
default="laion5B-H-14",
|
| 365 |
+
)
|
| 366 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 367 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 368 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 369 |
+
parser.add_argument("--no-register", action="store_true")
|
| 370 |
+
args = parser.parse_args()
|
| 371 |
+
logger.info(f"args: {args}")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
worker = ModelWorker(
|
| 375 |
+
args.controller_address,
|
| 376 |
+
args.worker_address,
|
| 377 |
+
worker_id,
|
| 378 |
+
args.no_register,
|
| 379 |
+
args.model_path,
|
| 380 |
+
args.model_names,
|
| 381 |
+
args.device,
|
| 382 |
+
args.indice_name,
|
| 383 |
+
)
|
| 384 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/constants.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import IntEnum
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
REPO_PATH = os.path.dirname(os.path.dirname(__file__))
|
| 5 |
+
|
| 6 |
+
##### For the gradio web server
|
| 7 |
+
SERVER_ERROR_MSG = (
|
| 8 |
+
"**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
| 9 |
+
)
|
| 10 |
+
MODERATION_MSG = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE FIX YOUR INPUT AND TRY AGAIN."
|
| 11 |
+
CONVERSATION_LIMIT_MSG = "YOU HAVE REACHED THE CONVERSATION LENGTH LIMIT. PLEASE CLEAR HISTORY AND START A NEW CONVERSATION."
|
| 12 |
+
INACTIVE_MSG = "THIS SESSION HAS BEEN INACTIVE FOR TOO LONG. PLEASE REFRESH THIS PAGE."
|
| 13 |
+
# Maximum input length
|
| 14 |
+
INPUT_CHAR_LEN_LIMIT = int(os.getenv("FASTCHAT_INPUT_CHAR_LEN_LIMIT", 2560))
|
| 15 |
+
# Maximum conversation turns
|
| 16 |
+
CONVERSATION_TURN_LIMIT = 50
|
| 17 |
+
# Session expiration time
|
| 18 |
+
SESSION_EXPIRATION_TIME = 3600
|
| 19 |
+
# The output dir of log files
|
| 20 |
+
LOGDIR = "."
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
##### For the controller and workers (could be overwritten through ENV variables.)
|
| 24 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = int(
|
| 25 |
+
os.getenv("FASTCHAT_CONTROLLER_HEART_BEAT_EXPIRATION", 90)
|
| 26 |
+
)
|
| 27 |
+
WORKER_HEART_BEAT_INTERVAL = int(os.getenv("FASTCHAT_WORKER_HEART_BEAT_INTERVAL", 45))
|
| 28 |
+
WORKER_API_TIMEOUT = int(os.getenv("FASTCHAT_WORKER_API_TIMEOUT", 100))
|
| 29 |
+
WORKER_API_EMBEDDING_BATCH_SIZE = int(
|
| 30 |
+
os.getenv("FASTCHAT_WORKER_API_EMBEDDING_BATCH_SIZE", 4)
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ErrorCode(IntEnum):
|
| 35 |
+
"""
|
| 36 |
+
https://platform.openai.com/docs/guides/error-codes/api-errors
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
VALIDATION_TYPE_ERROR = 40001
|
| 40 |
+
|
| 41 |
+
INVALID_AUTH_KEY = 40101
|
| 42 |
+
INCORRECT_AUTH_KEY = 40102
|
| 43 |
+
NO_PERMISSION = 40103
|
| 44 |
+
|
| 45 |
+
INVALID_MODEL = 40301
|
| 46 |
+
PARAM_OUT_OF_RANGE = 40302
|
| 47 |
+
CONTEXT_OVERFLOW = 40303
|
| 48 |
+
|
| 49 |
+
RATE_LIMIT = 42901
|
| 50 |
+
QUOTA_EXCEEDED = 42902
|
| 51 |
+
ENGINE_OVERLOADED = 42903
|
| 52 |
+
|
| 53 |
+
INTERNAL_ERROR = 50001
|
| 54 |
+
CUDA_OUT_OF_MEMORY = 50002
|
| 55 |
+
GRADIO_REQUEST_ERROR = 50003
|
| 56 |
+
GRADIO_STREAM_UNKNOWN_ERROR = 50004
|
| 57 |
+
CONTROLLER_NO_WORKER = 50005
|
| 58 |
+
CONTROLLER_WORKER_TIMEOUT = 50006
|
fin-mm/code/LLaVA-Plus/serve/controller.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A controller manages distributed workers.
|
| 3 |
+
It sends worker addresses to clients.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import uvicorn
|
| 7 |
+
import requests
|
| 8 |
+
import numpy as np
|
| 9 |
+
from fastapi.responses import StreamingResponse
|
| 10 |
+
from fastapi import FastAPI, Request
|
| 11 |
+
import threading
|
| 12 |
+
from typing import List, Union
|
| 13 |
+
import time
|
| 14 |
+
import logging
|
| 15 |
+
import json
|
| 16 |
+
from enum import Enum, auto
|
| 17 |
+
import dataclasses
|
| 18 |
+
import asyncio
|
| 19 |
+
import argparse
|
| 20 |
+
import sys
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 24 |
+
|
| 25 |
+
from serve.utils import build_logger, server_error_msg
|
| 26 |
+
from serve.constants import CONTROLLER_HEART_BEAT_EXPIRATION
|
| 27 |
+
|
| 28 |
+
logger = build_logger("controller", "controller.log")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DispatchMethod(Enum):
|
| 32 |
+
LOTTERY = auto()
|
| 33 |
+
SHORTEST_QUEUE = auto()
|
| 34 |
+
|
| 35 |
+
@classmethod
|
| 36 |
+
def from_str(cls, name):
|
| 37 |
+
if name == "lottery":
|
| 38 |
+
return cls.LOTTERY
|
| 39 |
+
elif name == "shortest_queue":
|
| 40 |
+
return cls.SHORTEST_QUEUE
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError(f"Invalid dispatch method")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclasses.dataclass
|
| 46 |
+
class WorkerInfo:
|
| 47 |
+
model_names: List[str]
|
| 48 |
+
speed: int
|
| 49 |
+
queue_length: int
|
| 50 |
+
check_heart_beat: bool
|
| 51 |
+
last_heart_beat: str
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def heart_beat_controller(controller):
|
| 55 |
+
while True:
|
| 56 |
+
time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
|
| 57 |
+
controller.remove_stable_workers_by_expiration()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Controller:
|
| 61 |
+
def __init__(self, dispatch_method: str):
|
| 62 |
+
# Dict[str -> WorkerInfo]
|
| 63 |
+
self.worker_info = {}
|
| 64 |
+
self.dispatch_method = DispatchMethod.from_str(dispatch_method)
|
| 65 |
+
|
| 66 |
+
self.heart_beat_thread = threading.Thread(
|
| 67 |
+
target=heart_beat_controller, args=(self,))
|
| 68 |
+
self.heart_beat_thread.start()
|
| 69 |
+
|
| 70 |
+
logger.info("Init controller")
|
| 71 |
+
|
| 72 |
+
def register_worker(self, worker_name: str, check_heart_beat: bool,
|
| 73 |
+
worker_status: dict):
|
| 74 |
+
if worker_name not in self.worker_info:
|
| 75 |
+
logger.info(f"Register a new worker: {worker_name}")
|
| 76 |
+
else:
|
| 77 |
+
logger.info(f"Register an existing worker: {worker_name}")
|
| 78 |
+
|
| 79 |
+
if not worker_status:
|
| 80 |
+
worker_status = self.get_worker_status(worker_name)
|
| 81 |
+
if not worker_status:
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
self.worker_info[worker_name] = WorkerInfo(
|
| 85 |
+
worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
|
| 86 |
+
check_heart_beat, time.time())
|
| 87 |
+
|
| 88 |
+
logger.info(f"Register done: {worker_name}, {worker_status}")
|
| 89 |
+
return True
|
| 90 |
+
|
| 91 |
+
def get_worker_status(self, worker_name: str):
|
| 92 |
+
try:
|
| 93 |
+
r = requests.post(worker_name + "/worker_get_status", timeout=5)
|
| 94 |
+
except requests.exceptions.RequestException as e:
|
| 95 |
+
logger.error(f"Get status fails: {worker_name}, {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
if r.status_code != 200:
|
| 99 |
+
logger.error(f"Get status fails: {worker_name}, {r}")
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
return r.json()
|
| 103 |
+
|
| 104 |
+
def remove_worker(self, worker_name: str):
|
| 105 |
+
del self.worker_info[worker_name]
|
| 106 |
+
|
| 107 |
+
def refresh_all_workers(self):
|
| 108 |
+
old_info = dict(self.worker_info)
|
| 109 |
+
self.worker_info = {}
|
| 110 |
+
|
| 111 |
+
for w_name, w_info in old_info.items():
|
| 112 |
+
if not self.register_worker(w_name, w_info.check_heart_beat, None):
|
| 113 |
+
logger.info(f"Remove stale worker: {w_name}")
|
| 114 |
+
|
| 115 |
+
def list_models(self):
|
| 116 |
+
model_names = set()
|
| 117 |
+
|
| 118 |
+
for w_name, w_info in self.worker_info.items():
|
| 119 |
+
model_names.update(w_info.model_names)
|
| 120 |
+
|
| 121 |
+
return list(model_names)
|
| 122 |
+
|
| 123 |
+
def get_worker_address(self, model_name: str):
|
| 124 |
+
if self.dispatch_method == DispatchMethod.LOTTERY:
|
| 125 |
+
worker_names = []
|
| 126 |
+
worker_speeds = []
|
| 127 |
+
for w_name, w_info in self.worker_info.items():
|
| 128 |
+
if model_name in w_info.model_names:
|
| 129 |
+
worker_names.append(w_name)
|
| 130 |
+
worker_speeds.append(w_info.speed)
|
| 131 |
+
worker_speeds = np.array(worker_speeds, dtype=np.float32)
|
| 132 |
+
norm = np.sum(worker_speeds)
|
| 133 |
+
if norm < 1e-4:
|
| 134 |
+
return ""
|
| 135 |
+
worker_speeds = worker_speeds / norm
|
| 136 |
+
if True: # Directly return address
|
| 137 |
+
pt = np.random.choice(np.arange(len(worker_names)),
|
| 138 |
+
p=worker_speeds)
|
| 139 |
+
worker_name = worker_names[pt]
|
| 140 |
+
return worker_name
|
| 141 |
+
|
| 142 |
+
# Check status before returning
|
| 143 |
+
while True:
|
| 144 |
+
pt = np.random.choice(np.arange(len(worker_names)),
|
| 145 |
+
p=worker_speeds)
|
| 146 |
+
worker_name = worker_names[pt]
|
| 147 |
+
|
| 148 |
+
if self.get_worker_status(worker_name):
|
| 149 |
+
break
|
| 150 |
+
else:
|
| 151 |
+
self.remove_worker(worker_name)
|
| 152 |
+
worker_speeds[pt] = 0
|
| 153 |
+
norm = np.sum(worker_speeds)
|
| 154 |
+
if norm < 1e-4:
|
| 155 |
+
return ""
|
| 156 |
+
worker_speeds = worker_speeds / norm
|
| 157 |
+
continue
|
| 158 |
+
return worker_name
|
| 159 |
+
elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
|
| 160 |
+
worker_names = []
|
| 161 |
+
worker_qlen = []
|
| 162 |
+
for w_name, w_info in self.worker_info.items():
|
| 163 |
+
if model_name in w_info.model_names:
|
| 164 |
+
worker_names.append(w_name)
|
| 165 |
+
worker_qlen.append(w_info.queue_length / w_info.speed)
|
| 166 |
+
if len(worker_names) == 0:
|
| 167 |
+
return ""
|
| 168 |
+
min_index = np.argmin(worker_qlen)
|
| 169 |
+
w_name = worker_names[min_index]
|
| 170 |
+
self.worker_info[w_name].queue_length += 1
|
| 171 |
+
logger.info(
|
| 172 |
+
f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
|
| 173 |
+
return w_name
|
| 174 |
+
else:
|
| 175 |
+
raise ValueError(
|
| 176 |
+
f"Invalid dispatch method: {self.dispatch_method}")
|
| 177 |
+
|
| 178 |
+
def receive_heart_beat(self, worker_name: str, queue_length: int):
|
| 179 |
+
if worker_name not in self.worker_info:
|
| 180 |
+
logger.info(f"Receive unknown heart beat. {worker_name}")
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
self.worker_info[worker_name].queue_length = queue_length
|
| 184 |
+
self.worker_info[worker_name].last_heart_beat = time.time()
|
| 185 |
+
logger.info(f"Receive heart beat. {worker_name}")
|
| 186 |
+
return True
|
| 187 |
+
|
| 188 |
+
def remove_stable_workers_by_expiration(self):
|
| 189 |
+
expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
|
| 190 |
+
to_delete = []
|
| 191 |
+
for worker_name, w_info in self.worker_info.items():
|
| 192 |
+
if w_info.check_heart_beat and w_info.last_heart_beat < expire:
|
| 193 |
+
to_delete.append(worker_name)
|
| 194 |
+
|
| 195 |
+
for worker_name in to_delete:
|
| 196 |
+
self.remove_worker(worker_name)
|
| 197 |
+
|
| 198 |
+
def worker_api_generate_stream(self, params):
|
| 199 |
+
worker_addr = self.get_worker_address(params["model"])
|
| 200 |
+
if not worker_addr:
|
| 201 |
+
logger.info(f"no worker: {params['model']}")
|
| 202 |
+
ret = {
|
| 203 |
+
"text": server_error_msg,
|
| 204 |
+
"error_code": 2,
|
| 205 |
+
}
|
| 206 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
response = requests.post(worker_addr + "/worker_generate_stream",
|
| 210 |
+
json=params, stream=True, timeout=5)
|
| 211 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 212 |
+
if chunk:
|
| 213 |
+
yield chunk + b"\0"
|
| 214 |
+
except requests.exceptions.RequestException as e:
|
| 215 |
+
logger.info(f"worker timeout: {worker_addr}")
|
| 216 |
+
ret = {
|
| 217 |
+
"text": server_error_msg,
|
| 218 |
+
"error_code": 3,
|
| 219 |
+
}
|
| 220 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 221 |
+
|
| 222 |
+
# Let the controller act as a worker to achieve hierarchical
|
| 223 |
+
# management. This can be used to connect isolated sub networks.
|
| 224 |
+
|
| 225 |
+
def worker_api_get_status(self):
|
| 226 |
+
model_names = set()
|
| 227 |
+
speed = 0
|
| 228 |
+
queue_length = 0
|
| 229 |
+
|
| 230 |
+
for w_name in self.worker_info:
|
| 231 |
+
worker_status = self.get_worker_status(w_name)
|
| 232 |
+
if worker_status is not None:
|
| 233 |
+
model_names.update(worker_status["model_names"])
|
| 234 |
+
speed += worker_status["speed"]
|
| 235 |
+
queue_length += worker_status["queue_length"]
|
| 236 |
+
|
| 237 |
+
return {
|
| 238 |
+
"model_names": list(model_names),
|
| 239 |
+
"speed": speed,
|
| 240 |
+
"queue_length": queue_length,
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
app = FastAPI()
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@app.post("/register_worker")
|
| 248 |
+
async def register_worker(request: Request):
|
| 249 |
+
data = await request.json()
|
| 250 |
+
controller.register_worker(
|
| 251 |
+
data["worker_name"], data["check_heart_beat"],
|
| 252 |
+
data.get("worker_status", None))
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@app.post("/refresh_all_workers")
|
| 256 |
+
async def refresh_all_workers():
|
| 257 |
+
models = controller.refresh_all_workers()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@app.post("/list_models")
|
| 261 |
+
async def list_models():
|
| 262 |
+
models = controller.list_models()
|
| 263 |
+
return {"models": models}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.post("/get_worker_address")
|
| 267 |
+
async def get_worker_address(request: Request):
|
| 268 |
+
data = await request.json()
|
| 269 |
+
addr = controller.get_worker_address(data["model"])
|
| 270 |
+
return {"address": addr}
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@app.post("/receive_heart_beat")
|
| 274 |
+
async def receive_heart_beat(request: Request):
|
| 275 |
+
data = await request.json()
|
| 276 |
+
exist = controller.receive_heart_beat(
|
| 277 |
+
data["worker_name"], data["queue_length"])
|
| 278 |
+
return {"exist": exist}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@app.post("/worker_generate_stream")
|
| 282 |
+
async def worker_api_generate_stream(request: Request):
|
| 283 |
+
params = await request.json()
|
| 284 |
+
generator = controller.worker_api_generate_stream(params)
|
| 285 |
+
return StreamingResponse(generator)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@app.post("/worker_get_status")
|
| 289 |
+
async def worker_api_get_status(request: Request):
|
| 290 |
+
return controller.worker_api_get_status()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == "__main__":
|
| 294 |
+
parser = argparse.ArgumentParser()
|
| 295 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 296 |
+
parser.add_argument("--port", type=int, default=21001)
|
| 297 |
+
parser.add_argument("--dispatch-method", type=str, choices=[
|
| 298 |
+
"lottery", "shortest_queue"], default="shortest_queue")
|
| 299 |
+
args = parser.parse_args()
|
| 300 |
+
logger.info(f"args: {args}")
|
| 301 |
+
|
| 302 |
+
controller = Controller(args.dispatch_method)
|
| 303 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/grounded_sam_test_message.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate, annotate_xyxy
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
import pycocotools.mask as mask_util
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_image(image_path):
|
| 22 |
+
img = Image.open(image_path).convert('RGB')
|
| 23 |
+
# import ipdb; ipdb.set_trace()
|
| 24 |
+
# resize if needed
|
| 25 |
+
w, h = img.size
|
| 26 |
+
if max(h, w) > 800:
|
| 27 |
+
if h > w:
|
| 28 |
+
new_h = 800
|
| 29 |
+
new_w = int(w * 800 / h)
|
| 30 |
+
else:
|
| 31 |
+
new_w = 800
|
| 32 |
+
new_h = int(h * 800 / w)
|
| 33 |
+
# import ipdb; ipdb.set_trace()
|
| 34 |
+
img = F.resize(img, (new_h, new_w))
|
| 35 |
+
return img
|
| 36 |
+
|
| 37 |
+
def encode(image: Image):
|
| 38 |
+
buffered = BytesIO()
|
| 39 |
+
image.save(buffered, format="JPEG")
|
| 40 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 41 |
+
return img_b64_str
|
| 42 |
+
|
| 43 |
+
def show_mask(mask, image, random_color=True):
|
| 44 |
+
if random_color:
|
| 45 |
+
color = np.concatenate([np.random.random(3), np.array([0.8])], axis=0)
|
| 46 |
+
else:
|
| 47 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 48 |
+
h, w = mask.shape[-2:]
|
| 49 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 50 |
+
|
| 51 |
+
annotated_frame_pil = Image.fromarray(image).convert("RGBA")
|
| 52 |
+
mask_image_pil = Image.fromarray((mask_image.cpu().numpy() * 255).astype(np.uint8)).convert("RGBA")
|
| 53 |
+
|
| 54 |
+
return np.array(Image.alpha_composite(annotated_frame_pil, mask_image_pil))
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
model_name = args.model_name
|
| 58 |
+
|
| 59 |
+
if args.worker_address:
|
| 60 |
+
worker_addr = args.worker_address
|
| 61 |
+
else:
|
| 62 |
+
controller_addr = args.controller_address
|
| 63 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 64 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 65 |
+
models = ret.json()["models"]
|
| 66 |
+
models.sort()
|
| 67 |
+
print(f"Models: {models}")
|
| 68 |
+
|
| 69 |
+
ret = requests.post(
|
| 70 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 71 |
+
)
|
| 72 |
+
worker_addr = ret.json()["address"]
|
| 73 |
+
print(f"worker_addr: {worker_addr}")
|
| 74 |
+
|
| 75 |
+
if worker_addr == "":
|
| 76 |
+
print(f"No available workers for {model_name}")
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 80 |
+
if args.send_image:
|
| 81 |
+
img = load_image(args.image_path)
|
| 82 |
+
img_arg = encode(img)
|
| 83 |
+
else:
|
| 84 |
+
img_arg = args.image_path
|
| 85 |
+
img = None
|
| 86 |
+
datas = {
|
| 87 |
+
"model": model_name,
|
| 88 |
+
"caption": args.caption,
|
| 89 |
+
"image": img_arg,
|
| 90 |
+
"box_threshold": args.box_threshold,
|
| 91 |
+
"text_threshold": args.text_threshold,
|
| 92 |
+
}
|
| 93 |
+
tic = time.time()
|
| 94 |
+
response = requests.post(
|
| 95 |
+
worker_addr + "/worker_generate",
|
| 96 |
+
headers=headers,
|
| 97 |
+
json=datas,
|
| 98 |
+
)
|
| 99 |
+
toc = time.time()
|
| 100 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 101 |
+
|
| 102 |
+
print("detection result:")
|
| 103 |
+
print(response.json())
|
| 104 |
+
# response is 'Response' with :
|
| 105 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 106 |
+
|
| 107 |
+
# visualize
|
| 108 |
+
res = response.json()
|
| 109 |
+
# import ipdb; ipdb.set_trace()
|
| 110 |
+
boxes = torch.Tensor(res["boxes"])
|
| 111 |
+
logits = torch.Tensor(res["logits"])
|
| 112 |
+
phrases = res["phrases"]
|
| 113 |
+
if img is not None:
|
| 114 |
+
image_source = np.array(img.convert("RGB"))
|
| 115 |
+
else:
|
| 116 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 117 |
+
annotated_frame = annotate_xyxy(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 118 |
+
# cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 119 |
+
|
| 120 |
+
# show mask
|
| 121 |
+
masks_rle = res["masks_rle"]
|
| 122 |
+
for mask_rle in masks_rle:
|
| 123 |
+
mask = mask_util.decode(mask_rle)
|
| 124 |
+
mask = torch.Tensor(mask)
|
| 125 |
+
annotated_frame = show_mask(mask, annotated_frame)
|
| 126 |
+
cv2.imwrite("annotated_image_mask.jpg", annotated_frame)
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
parser = argparse.ArgumentParser()
|
| 130 |
+
# worker parameters
|
| 131 |
+
parser.add_argument(
|
| 132 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument("--worker-address", type=str)
|
| 135 |
+
parser.add_argument("--model-name", type=str, default='grounded_sam')
|
| 136 |
+
|
| 137 |
+
# model parameters
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--caption", type=str, default="dogs ."
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 143 |
+
)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--box_threshold", type=float, default=0.3,
|
| 146 |
+
)
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--text_threshold", type=float, default=0.25,
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--send_image", action="store_true",
|
| 152 |
+
)
|
| 153 |
+
args = parser.parse_args()
|
| 154 |
+
|
| 155 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/grounded_sam_worker.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
from groundingdino.util import box_ops
|
| 6 |
+
|
| 7 |
+
from segment_anything import build_sam
|
| 8 |
+
from segment_anything.predictor import SamPredictor
|
| 9 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import asyncio
|
| 13 |
+
import dataclasses
|
| 14 |
+
import logging
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from typing import List, Tuple, Union
|
| 20 |
+
import threading
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
from io import BytesIO
|
| 24 |
+
import base64
|
| 25 |
+
|
| 26 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 27 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 28 |
+
import numpy as np
|
| 29 |
+
import requests
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 33 |
+
|
| 34 |
+
from groundingdino.util.inference import load_model, predict
|
| 35 |
+
import groundingdino.datasets.transforms as T
|
| 36 |
+
import pycocotools.mask as mask_util
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from transformers import (
|
| 41 |
+
AutoTokenizer,
|
| 42 |
+
AutoModelForCausalLM,
|
| 43 |
+
LlamaTokenizer,
|
| 44 |
+
AutoModel,
|
| 45 |
+
)
|
| 46 |
+
except ImportError:
|
| 47 |
+
from transformers import (
|
| 48 |
+
AutoTokenizer,
|
| 49 |
+
AutoModelForCausalLM,
|
| 50 |
+
LLaMATokenizer,
|
| 51 |
+
AutoModel,
|
| 52 |
+
)
|
| 53 |
+
import torch
|
| 54 |
+
import torch.nn.functional as F
|
| 55 |
+
import uvicorn
|
| 56 |
+
|
| 57 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 58 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 59 |
+
|
| 60 |
+
GB = 1 << 30
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
now_file_name = os.__file__
|
| 64 |
+
logdir = "logs/workers/"
|
| 65 |
+
os.makedirs(logdir, exist_ok=True)
|
| 66 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 67 |
+
|
| 68 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 69 |
+
logger = build_logger(now_file_name, logfile)
|
| 70 |
+
global_counter = 0
|
| 71 |
+
|
| 72 |
+
model_semaphore = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def heart_beat_worker(controller):
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 78 |
+
controller.send_heart_beat()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelWorker:
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
controller_addr,
|
| 85 |
+
worker_addr,
|
| 86 |
+
worker_id,
|
| 87 |
+
no_register,
|
| 88 |
+
model_path,
|
| 89 |
+
model_config,
|
| 90 |
+
model_names,
|
| 91 |
+
sam_path,
|
| 92 |
+
device,
|
| 93 |
+
grounding_dino_server=None,
|
| 94 |
+
sam_server=None,
|
| 95 |
+
):
|
| 96 |
+
self.controller_addr = controller_addr
|
| 97 |
+
self.worker_addr = worker_addr
|
| 98 |
+
self.worker_id = worker_id
|
| 99 |
+
if model_path.endswith("/"):
|
| 100 |
+
model_path = model_path[:-1]
|
| 101 |
+
self.model_names = model_names
|
| 102 |
+
self.model_config = model_config
|
| 103 |
+
self.device = device
|
| 104 |
+
self.grounding_dino_server = grounding_dino_server
|
| 105 |
+
|
| 106 |
+
if grounding_dino_server is None:
|
| 107 |
+
raise NotImplementedError("grounding_dino_server is None, we only support grounding_dino_server now.")
|
| 108 |
+
logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 109 |
+
self.model = load_model(
|
| 110 |
+
model_config_path=model_config,
|
| 111 |
+
model_checkpoint_path=model_path,
|
| 112 |
+
device=device,
|
| 113 |
+
)
|
| 114 |
+
self.model.to(device)
|
| 115 |
+
self.model.eval()
|
| 116 |
+
else:
|
| 117 |
+
self.model = None
|
| 118 |
+
# get grounding dino addr
|
| 119 |
+
if grounding_dino_server.startswith("http"):
|
| 120 |
+
grounding_dino_server_addr = grounding_dino_server
|
| 121 |
+
else:
|
| 122 |
+
controller_addr = self.controller_addr
|
| 123 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 124 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 125 |
+
models = ret.json()["models"]
|
| 126 |
+
models.sort()
|
| 127 |
+
print(f"Models: {models}")
|
| 128 |
+
|
| 129 |
+
ret = requests.post(
|
| 130 |
+
controller_addr + "/get_worker_address", json={"model": grounding_dino_server}
|
| 131 |
+
)
|
| 132 |
+
grounding_dino_server_addr = ret.json()["address"]
|
| 133 |
+
print(f"grounding_dino_server_addr: {grounding_dino_server_addr}")
|
| 134 |
+
self.grounding_dino_server_addr = grounding_dino_server_addr
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if not no_register:
|
| 138 |
+
self.register_to_controller()
|
| 139 |
+
self.heart_beat_thread = threading.Thread(
|
| 140 |
+
target=heart_beat_worker, args=(self,)
|
| 141 |
+
)
|
| 142 |
+
self.heart_beat_thread.start()
|
| 143 |
+
|
| 144 |
+
self.transform = T.Compose(
|
| 145 |
+
[
|
| 146 |
+
T.RandomResize([800], max_size=1333),
|
| 147 |
+
T.ToTensor(),
|
| 148 |
+
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 149 |
+
]
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# load sam model
|
| 153 |
+
self.sam_server = sam_server
|
| 154 |
+
if sam_server is None:
|
| 155 |
+
self.sam = build_sam(checkpoint=sam_path)
|
| 156 |
+
self.sam.to(device=device)
|
| 157 |
+
self.sam_predictor = SamPredictor(self.sam)
|
| 158 |
+
self.sam_server_addr = None
|
| 159 |
+
else:
|
| 160 |
+
self.sam = None
|
| 161 |
+
self.sam_predictor = None
|
| 162 |
+
# get grounding dino addr
|
| 163 |
+
if sam_server.startswith("http"):
|
| 164 |
+
sam_server_addr = sam_server
|
| 165 |
+
else:
|
| 166 |
+
time.sleep(3)
|
| 167 |
+
controller_addr = self.controller_addr
|
| 168 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 169 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 170 |
+
models = ret.json()["models"]
|
| 171 |
+
models.sort()
|
| 172 |
+
print(f"Models: {models}")
|
| 173 |
+
|
| 174 |
+
ret = requests.post(
|
| 175 |
+
controller_addr + "/get_worker_address", json={"model": sam_server}
|
| 176 |
+
)
|
| 177 |
+
sam_server_addr = ret.json()["address"]
|
| 178 |
+
print(f"sam_server_addr: {sam_server_addr}")
|
| 179 |
+
self.sam_server_addr = sam_server_addr
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def register_to_controller(self):
|
| 184 |
+
logger.info("Register to controller")
|
| 185 |
+
|
| 186 |
+
url = self.controller_addr + "/register_worker"
|
| 187 |
+
data = {
|
| 188 |
+
"worker_name": self.worker_addr,
|
| 189 |
+
"check_heart_beat": True,
|
| 190 |
+
"worker_status": self.get_status(),
|
| 191 |
+
}
|
| 192 |
+
r = requests.post(url, json=data)
|
| 193 |
+
assert r.status_code == 200
|
| 194 |
+
|
| 195 |
+
def send_heart_beat(self):
|
| 196 |
+
logger.info(
|
| 197 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 198 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 199 |
+
f"global_counter: {global_counter}. "
|
| 200 |
+
f"worker_id: {worker_id}. "
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 204 |
+
|
| 205 |
+
while True:
|
| 206 |
+
try:
|
| 207 |
+
ret = requests.post(
|
| 208 |
+
url,
|
| 209 |
+
json={
|
| 210 |
+
"worker_name": self.worker_addr,
|
| 211 |
+
"queue_length": self.get_queue_length(),
|
| 212 |
+
},
|
| 213 |
+
timeout=5,
|
| 214 |
+
)
|
| 215 |
+
exist = ret.json()["exist"]
|
| 216 |
+
break
|
| 217 |
+
except requests.exceptions.RequestException as e:
|
| 218 |
+
logger.error(f"heart beat error: {e}")
|
| 219 |
+
time.sleep(5)
|
| 220 |
+
|
| 221 |
+
if not exist:
|
| 222 |
+
self.register_to_controller()
|
| 223 |
+
|
| 224 |
+
def get_queue_length(self):
|
| 225 |
+
if (
|
| 226 |
+
model_semaphore is None
|
| 227 |
+
or model_semaphore._value is None
|
| 228 |
+
or model_semaphore._waiters is None
|
| 229 |
+
):
|
| 230 |
+
return 0
|
| 231 |
+
else:
|
| 232 |
+
return (
|
| 233 |
+
args.limit_model_concurrency
|
| 234 |
+
- model_semaphore._value
|
| 235 |
+
+ len(model_semaphore._waiters)
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def get_status(self):
|
| 239 |
+
return {
|
| 240 |
+
"model_names": self.model_names,
|
| 241 |
+
"speed": 1,
|
| 242 |
+
"queue_length": self.get_queue_length(),
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if os.path.exists(image_path):
|
| 249 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 250 |
+
else:
|
| 251 |
+
# base64 coding
|
| 252 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 253 |
+
|
| 254 |
+
image = np.asarray(image_source)
|
| 255 |
+
image_transformed, _ = self.transform(image_source, None)
|
| 256 |
+
return image, image_transformed
|
| 257 |
+
|
| 258 |
+
def generate_stream_func(self, model, params, device):
|
| 259 |
+
# get inputs
|
| 260 |
+
text_prompt = params["caption"]
|
| 261 |
+
image_path = params["image"]
|
| 262 |
+
box_threshold = params["box_threshold"]
|
| 263 |
+
text_threshold = params["text_threshold"]
|
| 264 |
+
|
| 265 |
+
image_np, image = self.load_image(image_path)
|
| 266 |
+
if self.grounding_dino_server is not None:
|
| 267 |
+
headers = {"User-Agent": "G-SAM Client"}
|
| 268 |
+
pred_dict = requests.post(
|
| 269 |
+
self.grounding_dino_server_addr + "/worker_generate",
|
| 270 |
+
headers=headers,
|
| 271 |
+
json=params,
|
| 272 |
+
).json()
|
| 273 |
+
boxes = pred_dict["boxes"]
|
| 274 |
+
logits = pred_dict["logits"]
|
| 275 |
+
phrases = pred_dict["phrases"]
|
| 276 |
+
h, w = pred_dict["size"]
|
| 277 |
+
else:
|
| 278 |
+
# load image and run models
|
| 279 |
+
boxes, logits, phrases = predict(
|
| 280 |
+
model=model,
|
| 281 |
+
image=image,
|
| 282 |
+
caption=text_prompt,
|
| 283 |
+
box_threshold=box_threshold,
|
| 284 |
+
text_threshold=text_threshold,
|
| 285 |
+
device=device
|
| 286 |
+
)
|
| 287 |
+
boxes = boxes.tolist()
|
| 288 |
+
# round to 2 decimal places
|
| 289 |
+
boxes = [[round(x, 2) for x in box] for box in boxes]
|
| 290 |
+
logits = logits.tolist()
|
| 291 |
+
logits = [round(x, 2) for x in logits]
|
| 292 |
+
|
| 293 |
+
h, w, _ = image_np.shape
|
| 294 |
+
pred_dict = {
|
| 295 |
+
"boxes": boxes,
|
| 296 |
+
"logits": logits,
|
| 297 |
+
"phrases": phrases,
|
| 298 |
+
"size": [h, w], # H,W
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
# add sam output
|
| 302 |
+
if len(boxes) > 0:
|
| 303 |
+
if self.sam_server_addr is None:
|
| 304 |
+
boxes_tensor = torch.Tensor(boxes).to(device)
|
| 305 |
+
boxes_xyxy = box_ops.box_cxcywh_to_xyxy(boxes_tensor) * torch.Tensor([w, h, w, h]).to(device)
|
| 306 |
+
self.sam_predictor.set_image(image_np)
|
| 307 |
+
transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_xyxy, image_np.shape[:2]).to(device)
|
| 308 |
+
# import ipdb; ipdb.set_trace()
|
| 309 |
+
masks, _, _ = self.sam_predictor.predict_torch(
|
| 310 |
+
point_coords = None,
|
| 311 |
+
point_labels = None,
|
| 312 |
+
boxes = transformed_boxes,
|
| 313 |
+
multimask_output = False,
|
| 314 |
+
)
|
| 315 |
+
masks = masks[:, 0] # B, H, W
|
| 316 |
+
|
| 317 |
+
# encoder masks to strs
|
| 318 |
+
maskrls_list = []
|
| 319 |
+
for mask in masks:
|
| 320 |
+
mask_rle = mask_util.encode(np.array(mask[:, :, None].cpu(), order="F"))[0]
|
| 321 |
+
mask_rle["counts"] = mask_rle["counts"].decode("utf-8")
|
| 322 |
+
maskrls_list.append(mask_rle)
|
| 323 |
+
else:
|
| 324 |
+
headers = {"User-Agent": "G-SAM Client"}
|
| 325 |
+
params['boxes'] = boxes
|
| 326 |
+
pred_dict_sam = requests.post(
|
| 327 |
+
self.sam_server_addr + "/worker_generate",
|
| 328 |
+
headers=headers,
|
| 329 |
+
json=params,
|
| 330 |
+
).json()
|
| 331 |
+
maskrls_list = pred_dict_sam['masks_rle']
|
| 332 |
+
else:
|
| 333 |
+
maskrls_list = []
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
pred_dict['masks_rle'] = maskrls_list
|
| 337 |
+
return pred_dict
|
| 338 |
+
|
| 339 |
+
def generate_gate(self, params):
|
| 340 |
+
try:
|
| 341 |
+
|
| 342 |
+
ret = {"text": "", "error_code": 0}
|
| 343 |
+
ret = self.generate_stream_func(
|
| 344 |
+
self.model,
|
| 345 |
+
params,
|
| 346 |
+
self.device,
|
| 347 |
+
)
|
| 348 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 349 |
+
ret = {
|
| 350 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 351 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 352 |
+
}
|
| 353 |
+
except (ValueError, RuntimeError) as e:
|
| 354 |
+
ret = {
|
| 355 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 356 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 357 |
+
}
|
| 358 |
+
return ret
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
app = FastAPI()
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def release_model_semaphore():
|
| 365 |
+
model_semaphore.release()
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def acquire_model_semaphore():
|
| 369 |
+
global model_semaphore, global_counter
|
| 370 |
+
global_counter += 1
|
| 371 |
+
if model_semaphore is None:
|
| 372 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 373 |
+
return model_semaphore.acquire()
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def create_background_tasks():
|
| 377 |
+
background_tasks = BackgroundTasks()
|
| 378 |
+
background_tasks.add_task(release_model_semaphore)
|
| 379 |
+
return background_tasks
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
@app.post("/worker_generate")
|
| 384 |
+
async def api_generate(request: Request):
|
| 385 |
+
params = await request.json()
|
| 386 |
+
await acquire_model_semaphore()
|
| 387 |
+
output = worker.generate_gate(params)
|
| 388 |
+
release_model_semaphore()
|
| 389 |
+
return JSONResponse(output)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
@app.post("/worker_get_status")
|
| 393 |
+
async def api_get_status(request: Request):
|
| 394 |
+
return worker.get_status()
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@app.post("/model_details")
|
| 401 |
+
async def model_details(request: Request):
|
| 402 |
+
return {"context_length": worker.context_len}
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
if __name__ == "__main__":
|
| 406 |
+
parser = argparse.ArgumentParser()
|
| 407 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 408 |
+
parser.add_argument("--port", type=int, default=21293)
|
| 409 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21293")
|
| 410 |
+
parser.add_argument(
|
| 411 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
parser.add_argument(
|
| 415 |
+
"--model-path", type=str, default="groundingdino_swint_ogc.pth"
|
| 416 |
+
)
|
| 417 |
+
parser.add_argument(
|
| 418 |
+
"--model-config", type=str, default="GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"
|
| 419 |
+
)
|
| 420 |
+
parser.add_argument(
|
| 421 |
+
"--sam-path", type=str, default="sam_vit_h_4b8939.pth"
|
| 422 |
+
)
|
| 423 |
+
parser.add_argument(
|
| 424 |
+
"--model-names",
|
| 425 |
+
default="grounding_dino+sam,grounded_sam",
|
| 426 |
+
type=lambda s: s.split(","),
|
| 427 |
+
help="Optional display comma separated names",
|
| 428 |
+
)
|
| 429 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 430 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 431 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 432 |
+
parser.add_argument("--no-register", action="store_true")
|
| 433 |
+
parser.add_argument("--grounding-dino-server", type=str, default="grounding_dino")
|
| 434 |
+
parser.add_argument("--sam-server", type=str, default="sam")
|
| 435 |
+
args = parser.parse_args()
|
| 436 |
+
logger.info(f"args: {args}")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
worker = ModelWorker(
|
| 440 |
+
args.controller_address,
|
| 441 |
+
args.worker_address,
|
| 442 |
+
worker_id,
|
| 443 |
+
args.no_register,
|
| 444 |
+
args.model_path,
|
| 445 |
+
args.model_config,
|
| 446 |
+
args.model_names,
|
| 447 |
+
args.sam_path,
|
| 448 |
+
args.device,
|
| 449 |
+
args.grounding_dino_server,
|
| 450 |
+
args.sam_server,
|
| 451 |
+
)
|
| 452 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/grounding_dino_test_message.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate, annotate_xyxy
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"caption": args.caption,
|
| 73 |
+
"image": img_arg,
|
| 74 |
+
"box_threshold": args.box_threshold,
|
| 75 |
+
"text_threshold": args.text_threshold,
|
| 76 |
+
}
|
| 77 |
+
tic = time.time()
|
| 78 |
+
response = requests.post(
|
| 79 |
+
worker_addr + "/worker_generate",
|
| 80 |
+
headers=headers,
|
| 81 |
+
json=datas,
|
| 82 |
+
)
|
| 83 |
+
toc = time.time()
|
| 84 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 85 |
+
|
| 86 |
+
print("detection result:")
|
| 87 |
+
print(response.json())
|
| 88 |
+
# response is 'Response' with :
|
| 89 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 90 |
+
|
| 91 |
+
# visualize
|
| 92 |
+
res = response.json()
|
| 93 |
+
boxes = torch.Tensor(res["boxes"])
|
| 94 |
+
logits = torch.Tensor(res["logits"])
|
| 95 |
+
phrases = res["phrases"]
|
| 96 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 97 |
+
annotated_frame = annotate_xyxy(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 98 |
+
cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
parser = argparse.ArgumentParser()
|
| 103 |
+
# worker parameters
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument("--worker-address", type=str)
|
| 108 |
+
parser.add_argument("--model-name", type=str, default='grounding_dino')
|
| 109 |
+
|
| 110 |
+
# model parameters
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--caption", type=str, default="dogs ."
|
| 113 |
+
)
|
| 114 |
+
parser.add_argument(
|
| 115 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--box_threshold", type=float, default=0.3,
|
| 119 |
+
)
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--text_threshold", type=float, default=0.25,
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--send_image", action="store_true",
|
| 125 |
+
)
|
| 126 |
+
args = parser.parse_args()
|
| 127 |
+
|
| 128 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/grounding_dino_worker.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
|
| 6 |
+
from groundingdino.util import box_ops
|
| 7 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import asyncio
|
| 11 |
+
import dataclasses
|
| 12 |
+
import logging
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from typing import List, Tuple, Union
|
| 18 |
+
import threading
|
| 19 |
+
import uuid
|
| 20 |
+
import torchvision
|
| 21 |
+
|
| 22 |
+
from io import BytesIO
|
| 23 |
+
import base64
|
| 24 |
+
|
| 25 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 26 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 27 |
+
import numpy as np
|
| 28 |
+
import requests
|
| 29 |
+
from PIL import Image
|
| 30 |
+
|
| 31 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 32 |
+
|
| 33 |
+
from groundingdino.util.inference import load_model, predict
|
| 34 |
+
import groundingdino.datasets.transforms as T
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from transformers import (
|
| 39 |
+
AutoTokenizer,
|
| 40 |
+
AutoModelForCausalLM,
|
| 41 |
+
LlamaTokenizer,
|
| 42 |
+
AutoModel,
|
| 43 |
+
)
|
| 44 |
+
except ImportError:
|
| 45 |
+
from transformers import (
|
| 46 |
+
AutoTokenizer,
|
| 47 |
+
AutoModelForCausalLM,
|
| 48 |
+
LLaMATokenizer,
|
| 49 |
+
AutoModel,
|
| 50 |
+
)
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn.functional as F
|
| 53 |
+
import uvicorn
|
| 54 |
+
|
| 55 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 56 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 57 |
+
|
| 58 |
+
GB = 1 << 30
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
now_file_name = os.__file__
|
| 62 |
+
logdir = "logs/workers/"
|
| 63 |
+
os.makedirs(logdir, exist_ok=True)
|
| 64 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 65 |
+
|
| 66 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 67 |
+
logger = build_logger(now_file_name, logfile)
|
| 68 |
+
global_counter = 0
|
| 69 |
+
|
| 70 |
+
model_semaphore = None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def heart_beat_worker(controller):
|
| 74 |
+
while True:
|
| 75 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 76 |
+
controller.send_heart_beat()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class ModelWorker:
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
controller_addr,
|
| 83 |
+
worker_addr,
|
| 84 |
+
worker_id,
|
| 85 |
+
no_register,
|
| 86 |
+
model_path,
|
| 87 |
+
model_config,
|
| 88 |
+
model_names,
|
| 89 |
+
device,
|
| 90 |
+
):
|
| 91 |
+
self.controller_addr = controller_addr
|
| 92 |
+
self.worker_addr = worker_addr
|
| 93 |
+
self.worker_id = worker_id
|
| 94 |
+
if model_path.endswith("/"):
|
| 95 |
+
model_path = model_path[:-1]
|
| 96 |
+
self.model_names = model_names or [model_path.split("/")[-1]]
|
| 97 |
+
self.model_config = model_config
|
| 98 |
+
self.device = device
|
| 99 |
+
|
| 100 |
+
logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 101 |
+
self.model = load_model(
|
| 102 |
+
model_config_path=model_config,
|
| 103 |
+
model_checkpoint_path=model_path,
|
| 104 |
+
device=device,
|
| 105 |
+
)
|
| 106 |
+
self.model.to(device)
|
| 107 |
+
self.model.eval()
|
| 108 |
+
|
| 109 |
+
if not no_register:
|
| 110 |
+
self.register_to_controller()
|
| 111 |
+
self.heart_beat_thread = threading.Thread(
|
| 112 |
+
target=heart_beat_worker, args=(self,)
|
| 113 |
+
)
|
| 114 |
+
self.heart_beat_thread.start()
|
| 115 |
+
|
| 116 |
+
self.transform = T.Compose(
|
| 117 |
+
[
|
| 118 |
+
T.RandomResize([800], max_size=1333),
|
| 119 |
+
T.ToTensor(),
|
| 120 |
+
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 121 |
+
]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def register_to_controller(self):
|
| 125 |
+
logger.info("Register to controller")
|
| 126 |
+
|
| 127 |
+
url = self.controller_addr + "/register_worker"
|
| 128 |
+
data = {
|
| 129 |
+
"worker_name": self.worker_addr,
|
| 130 |
+
"check_heart_beat": True,
|
| 131 |
+
"worker_status": self.get_status(),
|
| 132 |
+
}
|
| 133 |
+
r = requests.post(url, json=data)
|
| 134 |
+
assert r.status_code == 200
|
| 135 |
+
|
| 136 |
+
def send_heart_beat(self):
|
| 137 |
+
logger.info(
|
| 138 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 139 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 140 |
+
f"global_counter: {global_counter}. "
|
| 141 |
+
f"worker_id: {worker_id}. "
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 145 |
+
|
| 146 |
+
while True:
|
| 147 |
+
try:
|
| 148 |
+
ret = requests.post(
|
| 149 |
+
url,
|
| 150 |
+
json={
|
| 151 |
+
"worker_name": self.worker_addr,
|
| 152 |
+
"queue_length": self.get_queue_length(),
|
| 153 |
+
},
|
| 154 |
+
timeout=5,
|
| 155 |
+
)
|
| 156 |
+
exist = ret.json()["exist"]
|
| 157 |
+
break
|
| 158 |
+
except requests.exceptions.RequestException as e:
|
| 159 |
+
logger.error(f"heart beat error: {e}")
|
| 160 |
+
time.sleep(5)
|
| 161 |
+
|
| 162 |
+
if not exist:
|
| 163 |
+
self.register_to_controller()
|
| 164 |
+
|
| 165 |
+
def get_queue_length(self):
|
| 166 |
+
if (
|
| 167 |
+
model_semaphore is None
|
| 168 |
+
or model_semaphore._value is None
|
| 169 |
+
or model_semaphore._waiters is None
|
| 170 |
+
):
|
| 171 |
+
return 0
|
| 172 |
+
else:
|
| 173 |
+
return (
|
| 174 |
+
args.limit_model_concurrency
|
| 175 |
+
- model_semaphore._value
|
| 176 |
+
+ len(model_semaphore._waiters)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def get_status(self):
|
| 180 |
+
return {
|
| 181 |
+
"model_names": self.model_names,
|
| 182 |
+
"speed": 1,
|
| 183 |
+
"queue_length": self.get_queue_length(),
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if os.path.exists(image_path):
|
| 190 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 191 |
+
else:
|
| 192 |
+
# base64 coding
|
| 193 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 194 |
+
|
| 195 |
+
image = np.asarray(image_source)
|
| 196 |
+
image_transformed, _ = self.transform(image_source, None)
|
| 197 |
+
return image, image_transformed
|
| 198 |
+
|
| 199 |
+
def generate_stream_func(self, model, params, device):
|
| 200 |
+
# get inputs
|
| 201 |
+
text_prompt = params["caption"]
|
| 202 |
+
image_path = params["image"]
|
| 203 |
+
box_threshold = params["box_threshold"]
|
| 204 |
+
text_threshold = params["text_threshold"]
|
| 205 |
+
|
| 206 |
+
# load image and run models
|
| 207 |
+
image_np, image = self.load_image(image_path)
|
| 208 |
+
boxes, logits, phrases = predict(
|
| 209 |
+
model=model,
|
| 210 |
+
image=image,
|
| 211 |
+
caption=text_prompt,
|
| 212 |
+
box_threshold=box_threshold,
|
| 213 |
+
text_threshold=text_threshold,
|
| 214 |
+
device=device
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# add NMS to boxes
|
| 218 |
+
boxes, logits, phrases = self.nms(boxes, logits, phrases)
|
| 219 |
+
boxes = box_ops.box_cxcywh_to_xyxy(boxes)
|
| 220 |
+
|
| 221 |
+
# import ipdb; ipdb.set_trace()
|
| 222 |
+
|
| 223 |
+
# to list format
|
| 224 |
+
boxes = boxes.tolist()
|
| 225 |
+
# round to 2 decimal places
|
| 226 |
+
boxes = [[round(x, 2) for x in box] for box in boxes]
|
| 227 |
+
logits = logits.tolist()
|
| 228 |
+
logits = [round(x, 2) for x in logits]
|
| 229 |
+
|
| 230 |
+
h, w, _ = image_np.shape
|
| 231 |
+
pred_dict = {
|
| 232 |
+
"boxes": boxes,
|
| 233 |
+
"logits": logits,
|
| 234 |
+
"phrases": phrases,
|
| 235 |
+
"size": [h, w], # H,W
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
return pred_dict
|
| 239 |
+
|
| 240 |
+
def nms(self, boxes, logits, phrases):
|
| 241 |
+
iou_threshold = 0.8
|
| 242 |
+
boxes_xyxy = box_ops.box_cxcywh_to_xyxy(boxes)
|
| 243 |
+
print(f"Before NMS: {boxes_xyxy.shape[0]} boxes")
|
| 244 |
+
nms_idx = torchvision.ops.nms(boxes_xyxy, logits, iou_threshold)
|
| 245 |
+
|
| 246 |
+
boxes = boxes[nms_idx]
|
| 247 |
+
logits = logits[nms_idx]
|
| 248 |
+
phrases = [phrases[idx] for idx in nms_idx]
|
| 249 |
+
print(f"After NMS: {boxes.shape[0]} boxes")
|
| 250 |
+
|
| 251 |
+
return boxes, logits, phrases
|
| 252 |
+
|
| 253 |
+
def generate_gate(self, params):
|
| 254 |
+
try:
|
| 255 |
+
|
| 256 |
+
ret = {"text": "", "error_code": 0}
|
| 257 |
+
ret = self.generate_stream_func(
|
| 258 |
+
self.model,
|
| 259 |
+
params,
|
| 260 |
+
self.device,
|
| 261 |
+
)
|
| 262 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 263 |
+
ret = {
|
| 264 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 265 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 266 |
+
}
|
| 267 |
+
except (ValueError, RuntimeError) as e:
|
| 268 |
+
ret = {
|
| 269 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 270 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 271 |
+
}
|
| 272 |
+
return ret
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
app = FastAPI()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def release_model_semaphore():
|
| 279 |
+
model_semaphore.release()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def acquire_model_semaphore():
|
| 283 |
+
global model_semaphore, global_counter
|
| 284 |
+
global_counter += 1
|
| 285 |
+
if model_semaphore is None:
|
| 286 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 287 |
+
return model_semaphore.acquire()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def create_background_tasks():
|
| 291 |
+
background_tasks = BackgroundTasks()
|
| 292 |
+
background_tasks.add_task(release_model_semaphore)
|
| 293 |
+
return background_tasks
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@app.post("/worker_generate")
|
| 298 |
+
async def api_generate(request: Request):
|
| 299 |
+
params = await request.json()
|
| 300 |
+
await acquire_model_semaphore()
|
| 301 |
+
output = worker.generate_gate(params)
|
| 302 |
+
release_model_semaphore()
|
| 303 |
+
return JSONResponse(output)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@app.post("/worker_get_status")
|
| 307 |
+
async def api_get_status(request: Request):
|
| 308 |
+
return worker.get_status()
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@app.post("/model_details")
|
| 315 |
+
async def model_details(request: Request):
|
| 316 |
+
return {"context_length": worker.context_len}
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
parser = argparse.ArgumentParser()
|
| 321 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 322 |
+
parser.add_argument("--port", type=int, default=21003)
|
| 323 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21003")
|
| 324 |
+
parser.add_argument(
|
| 325 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
parser.add_argument(
|
| 329 |
+
"--model-path", type=str, default="groundingdino_swint_ogc.pth"
|
| 330 |
+
)
|
| 331 |
+
parser.add_argument(
|
| 332 |
+
"--model-config", type=str, default="GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"
|
| 333 |
+
)
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--model-names",
|
| 336 |
+
default="grounding_dino",
|
| 337 |
+
type=lambda s: s.split(","),
|
| 338 |
+
help="Optional display comma separated names",
|
| 339 |
+
)
|
| 340 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 341 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 342 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 343 |
+
parser.add_argument("--no-register", action="store_true")
|
| 344 |
+
args = parser.parse_args()
|
| 345 |
+
logger.info(f"args: {args}")
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
worker = ModelWorker(
|
| 349 |
+
args.controller_address,
|
| 350 |
+
args.worker_address,
|
| 351 |
+
worker_id,
|
| 352 |
+
args.no_register,
|
| 353 |
+
args.model_path,
|
| 354 |
+
args.model_config,
|
| 355 |
+
args.model_names,
|
| 356 |
+
args.device,
|
| 357 |
+
)
|
| 358 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/inpainting_message.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate, annotate_xyxy
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
import pycocotools.mask as mask_util
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_image(image_path):
|
| 22 |
+
img = Image.open(image_path).convert('RGB')
|
| 23 |
+
# import ipdb; ipdb.set_trace()
|
| 24 |
+
# resize if needed
|
| 25 |
+
w, h = img.size
|
| 26 |
+
if max(h, w) > 800:
|
| 27 |
+
if h > w:
|
| 28 |
+
new_h = 800
|
| 29 |
+
new_w = int(w * 800 / h)
|
| 30 |
+
else:
|
| 31 |
+
new_w = 800
|
| 32 |
+
new_h = int(h * 800 / w)
|
| 33 |
+
# import ipdb; ipdb.set_trace()
|
| 34 |
+
img = F.resize(img, (new_h, new_w))
|
| 35 |
+
return img
|
| 36 |
+
|
| 37 |
+
def encode(image: Image):
|
| 38 |
+
buffered = BytesIO()
|
| 39 |
+
image.save(buffered, format="JPEG")
|
| 40 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 41 |
+
return img_b64_str
|
| 42 |
+
|
| 43 |
+
def show_mask(mask, image, random_color=True):
|
| 44 |
+
if random_color:
|
| 45 |
+
color = np.concatenate([np.random.random(3), np.array([0.8])], axis=0)
|
| 46 |
+
else:
|
| 47 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 48 |
+
h, w = mask.shape[-2:]
|
| 49 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 50 |
+
|
| 51 |
+
annotated_frame_pil = Image.fromarray(image).convert("RGBA")
|
| 52 |
+
mask_image_pil = Image.fromarray((mask_image.cpu().numpy() * 255).astype(np.uint8)).convert("RGBA")
|
| 53 |
+
|
| 54 |
+
return np.array(Image.alpha_composite(annotated_frame_pil, mask_image_pil))
|
| 55 |
+
|
| 56 |
+
def get_worker_addr(model_name, args):
|
| 57 |
+
if args.worker_address:
|
| 58 |
+
worker_addr = args.worker_address
|
| 59 |
+
else:
|
| 60 |
+
controller_addr = args.controller_address
|
| 61 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 62 |
+
_ = ret.json()
|
| 63 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 64 |
+
models = ret.json()["models"]
|
| 65 |
+
models.sort()
|
| 66 |
+
print(f"Models: {models}")
|
| 67 |
+
|
| 68 |
+
ret = requests.post(
|
| 69 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 70 |
+
)
|
| 71 |
+
worker_addr = ret.json()["address"]
|
| 72 |
+
print(f"worker_addr: {worker_addr}")
|
| 73 |
+
|
| 74 |
+
return worker_addr
|
| 75 |
+
def main():
|
| 76 |
+
model_name = args.model_name
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
sam_worker_addr = get_worker_addr("sam", args)
|
| 80 |
+
inpainting_worker_addr = get_worker_addr("inpainting", args)
|
| 81 |
+
if sam_worker_addr == "" or inpainting_worker_addr == "":
|
| 82 |
+
print(f"No available workers for {model_name}")
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 86 |
+
if args.send_image:
|
| 87 |
+
img = load_image(args.image_path)
|
| 88 |
+
img_arg = encode(img)
|
| 89 |
+
else:
|
| 90 |
+
img_arg = args.image_path
|
| 91 |
+
img = None
|
| 92 |
+
|
| 93 |
+
datas = {
|
| 94 |
+
"model": model_name,
|
| 95 |
+
"image": img_arg,
|
| 96 |
+
"boxes": args.boxes,
|
| 97 |
+
}
|
| 98 |
+
tic = time.time()
|
| 99 |
+
response = requests.post(
|
| 100 |
+
sam_worker_addr + "/worker_generate",
|
| 101 |
+
headers=headers,
|
| 102 |
+
json=datas,
|
| 103 |
+
)
|
| 104 |
+
toc = time.time()
|
| 105 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 106 |
+
|
| 107 |
+
print("segmentation result:")
|
| 108 |
+
print(response.json())
|
| 109 |
+
|
| 110 |
+
# visualize
|
| 111 |
+
res = response.json()
|
| 112 |
+
res['boxes'] = args.boxes
|
| 113 |
+
boxes = torch.Tensor(res["boxes"])
|
| 114 |
+
logits = torch.ones(boxes.shape[0])
|
| 115 |
+
phrases = ['' for _ in range(boxes.shape[0])]
|
| 116 |
+
if img is not None:
|
| 117 |
+
image_source = np.array(img.convert("RGB"))
|
| 118 |
+
else:
|
| 119 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 120 |
+
annotated_frame = annotate_xyxy(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 121 |
+
# cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 122 |
+
|
| 123 |
+
# show mask
|
| 124 |
+
masks_rle_list = res["masks_rle"]
|
| 125 |
+
for mask_rle in masks_rle_list:
|
| 126 |
+
mask = mask_util.decode(mask_rle)
|
| 127 |
+
mask = torch.Tensor(mask)
|
| 128 |
+
annotated_frame = show_mask(mask, annotated_frame)
|
| 129 |
+
cv2.imwrite("inpainting_1.jpg", annotated_frame)
|
| 130 |
+
|
| 131 |
+
_mask = Image.fromarray(mask_util.decode(masks_rle_list[1]) * 255)
|
| 132 |
+
_mask.save("inpainting_mask.jpg")
|
| 133 |
+
# import ipdb; ipdb.set_trace()
|
| 134 |
+
|
| 135 |
+
# inpainting
|
| 136 |
+
datas = {
|
| 137 |
+
"image": img_arg,
|
| 138 |
+
"mask": masks_rle_list[1],
|
| 139 |
+
"prompt": args.prompt,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
tic = time.time()
|
| 143 |
+
response = requests.post(
|
| 144 |
+
inpainting_worker_addr + "/worker_generate",
|
| 145 |
+
headers=headers,
|
| 146 |
+
json=datas,
|
| 147 |
+
)
|
| 148 |
+
toc = time.time()
|
| 149 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 150 |
+
|
| 151 |
+
res = response.json()
|
| 152 |
+
image = Image.open(BytesIO(base64.b64decode(res['edited_image']))).convert("RGB")
|
| 153 |
+
# import ipdb; ipdb.set_trace()
|
| 154 |
+
# save
|
| 155 |
+
image.save("inpainting_2.jpg")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
parser = argparse.ArgumentParser()
|
| 162 |
+
# worker parameters
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 165 |
+
)
|
| 166 |
+
parser.add_argument("--worker-address", type=str)
|
| 167 |
+
parser.add_argument("--model-name", type=str, default='sam')
|
| 168 |
+
|
| 169 |
+
# model parameters
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--prompt", type=str, default="flowers"
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--boxes",
|
| 175 |
+
default="[[0.1, 0.2, 0.8, 0.5], [0.3, 0.5, 0.9, 0.9]]",
|
| 176 |
+
type=lambda s: eval(s),
|
| 177 |
+
help="Optional display comma separated names",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--image_path", type=str, default="assets/demo2.jpg"
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--send_image", action="store_true",
|
| 184 |
+
)
|
| 185 |
+
args = parser.parse_args()
|
| 186 |
+
|
| 187 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/inpainting_worker.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import asyncio
|
| 9 |
+
import dataclasses
|
| 10 |
+
import logging
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from typing import List, Tuple, Union
|
| 16 |
+
import threading
|
| 17 |
+
import uuid
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
import base64
|
| 21 |
+
|
| 22 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 23 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 24 |
+
import numpy as np
|
| 25 |
+
import requests
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 29 |
+
|
| 30 |
+
from groundingdino.util.inference import load_model, predict
|
| 31 |
+
import groundingdino.datasets.transforms as T
|
| 32 |
+
from diffusers import StableDiffusionInpaintPipeline
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from transformers import (
|
| 37 |
+
AutoTokenizer,
|
| 38 |
+
AutoModelForCausalLM,
|
| 39 |
+
LlamaTokenizer,
|
| 40 |
+
AutoModel,
|
| 41 |
+
)
|
| 42 |
+
except ImportError:
|
| 43 |
+
from transformers import (
|
| 44 |
+
AutoTokenizer,
|
| 45 |
+
AutoModelForCausalLM,
|
| 46 |
+
LLaMATokenizer,
|
| 47 |
+
AutoModel,
|
| 48 |
+
)
|
| 49 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn.functional as F
|
| 53 |
+
import uvicorn
|
| 54 |
+
|
| 55 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 56 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 57 |
+
|
| 58 |
+
import pycocotools.mask as mask_util
|
| 59 |
+
|
| 60 |
+
GB = 1 << 30
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
now_file_name = os.__file__
|
| 64 |
+
logdir = "logs/workers/"
|
| 65 |
+
os.makedirs(logdir, exist_ok=True)
|
| 66 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 67 |
+
|
| 68 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 69 |
+
logger = build_logger(now_file_name, logfile)
|
| 70 |
+
global_counter = 0
|
| 71 |
+
|
| 72 |
+
model_semaphore = None
|
| 73 |
+
|
| 74 |
+
def encode(image: Image):
|
| 75 |
+
buffered = BytesIO()
|
| 76 |
+
image.save(buffered, format="JPEG")
|
| 77 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 78 |
+
return img_b64_str
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def heart_beat_worker(controller):
|
| 82 |
+
while True:
|
| 83 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 84 |
+
controller.send_heart_beat()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ModelWorker:
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
controller_addr,
|
| 91 |
+
worker_addr,
|
| 92 |
+
worker_id,
|
| 93 |
+
no_register,
|
| 94 |
+
model_path,
|
| 95 |
+
model_names,
|
| 96 |
+
device,
|
| 97 |
+
):
|
| 98 |
+
self.controller_addr = controller_addr
|
| 99 |
+
self.worker_addr = worker_addr
|
| 100 |
+
self.worker_id = worker_id
|
| 101 |
+
self.model_names = model_names
|
| 102 |
+
self.device = device
|
| 103 |
+
|
| 104 |
+
# # load model
|
| 105 |
+
pipe = StableDiffusionInpaintPipeline.from_pretrained(
|
| 106 |
+
"stabilityai/stable-diffusion-2-inpainting",
|
| 107 |
+
torch_dtype=torch.float16,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
pipe = pipe.to("cuda")
|
| 111 |
+
|
| 112 |
+
self.pipe = pipe
|
| 113 |
+
|
| 114 |
+
if not no_register:
|
| 115 |
+
self.register_to_controller()
|
| 116 |
+
self.heart_beat_thread = threading.Thread(
|
| 117 |
+
target=heart_beat_worker, args=(self,)
|
| 118 |
+
)
|
| 119 |
+
self.heart_beat_thread.start()
|
| 120 |
+
|
| 121 |
+
def resize(self, image:Image, resize_w:int, resize_h:int):
|
| 122 |
+
image = image.resize((resize_w, resize_h))
|
| 123 |
+
return image
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def register_to_controller(self):
|
| 127 |
+
logger.info("Register to controller")
|
| 128 |
+
|
| 129 |
+
url = self.controller_addr + "/register_worker"
|
| 130 |
+
data = {
|
| 131 |
+
"worker_name": self.worker_addr,
|
| 132 |
+
"check_heart_beat": True,
|
| 133 |
+
"worker_status": self.get_status(),
|
| 134 |
+
}
|
| 135 |
+
r = requests.post(url, json=data)
|
| 136 |
+
assert r.status_code == 200
|
| 137 |
+
|
| 138 |
+
def send_heart_beat(self):
|
| 139 |
+
logger.info(
|
| 140 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 141 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 142 |
+
f"global_counter: {global_counter}. "
|
| 143 |
+
f"worker_id: {worker_id}. "
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 147 |
+
|
| 148 |
+
while True:
|
| 149 |
+
try:
|
| 150 |
+
ret = requests.post(
|
| 151 |
+
url,
|
| 152 |
+
json={
|
| 153 |
+
"worker_name": self.worker_addr,
|
| 154 |
+
"queue_length": self.get_queue_length(),
|
| 155 |
+
},
|
| 156 |
+
timeout=5,
|
| 157 |
+
)
|
| 158 |
+
exist = ret.json()["exist"]
|
| 159 |
+
break
|
| 160 |
+
except requests.exceptions.RequestException as e:
|
| 161 |
+
logger.error(f"heart beat error: {e}")
|
| 162 |
+
time.sleep(5)
|
| 163 |
+
|
| 164 |
+
if not exist:
|
| 165 |
+
self.register_to_controller()
|
| 166 |
+
|
| 167 |
+
def get_queue_length(self):
|
| 168 |
+
if (
|
| 169 |
+
model_semaphore is None
|
| 170 |
+
or model_semaphore._value is None
|
| 171 |
+
or model_semaphore._waiters is None
|
| 172 |
+
):
|
| 173 |
+
return 0
|
| 174 |
+
else:
|
| 175 |
+
return (
|
| 176 |
+
args.limit_model_concurrency
|
| 177 |
+
- model_semaphore._value
|
| 178 |
+
+ len(model_semaphore._waiters)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def get_status(self):
|
| 182 |
+
return {
|
| 183 |
+
"model_names": self.model_names,
|
| 184 |
+
"speed": 1,
|
| 185 |
+
"queue_length": self.get_queue_length(),
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if os.path.exists(image_path):
|
| 192 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 193 |
+
else:
|
| 194 |
+
# base64 coding
|
| 195 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 196 |
+
|
| 197 |
+
return image_source
|
| 198 |
+
|
| 199 |
+
def generate_stream_func(self, model, params, device):
|
| 200 |
+
# get inputs
|
| 201 |
+
image_path = params["image"]
|
| 202 |
+
prompt = params["prompt"]
|
| 203 |
+
mask_rle = params["mask"] # rle
|
| 204 |
+
|
| 205 |
+
# load image and run models
|
| 206 |
+
image = self.load_image(image_path)
|
| 207 |
+
mask = Image.fromarray(mask_util.decode(mask_rle) * 255)
|
| 208 |
+
|
| 209 |
+
# resize to 512, 512
|
| 210 |
+
w, h = image.size
|
| 211 |
+
image = self.resize(image, 512, 512)
|
| 212 |
+
mask = self.resize(mask, 512, 512)
|
| 213 |
+
|
| 214 |
+
# run
|
| 215 |
+
images = self.pipe(prompt, image=image, mask_image=mask).images
|
| 216 |
+
image = images[0]
|
| 217 |
+
|
| 218 |
+
# re-resize
|
| 219 |
+
image = self.resize(image, w, h)
|
| 220 |
+
|
| 221 |
+
pred_dict = {
|
| 222 |
+
"edited_image": encode(image),
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
return pred_dict
|
| 226 |
+
|
| 227 |
+
def generate_gate(self, params):
|
| 228 |
+
try:
|
| 229 |
+
|
| 230 |
+
ret = {"text": "", "error_code": 0}
|
| 231 |
+
ret = self.generate_stream_func(
|
| 232 |
+
None,
|
| 233 |
+
params,
|
| 234 |
+
self.device,
|
| 235 |
+
)
|
| 236 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 237 |
+
ret = {
|
| 238 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 239 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 240 |
+
}
|
| 241 |
+
except (ValueError, RuntimeError) as e:
|
| 242 |
+
ret = {
|
| 243 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 244 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 245 |
+
}
|
| 246 |
+
return ret
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
app = FastAPI()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def release_model_semaphore():
|
| 254 |
+
model_semaphore.release()
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def acquire_model_semaphore():
|
| 258 |
+
global model_semaphore, global_counter
|
| 259 |
+
global_counter += 1
|
| 260 |
+
if model_semaphore is None:
|
| 261 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 262 |
+
return model_semaphore.acquire()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def create_background_tasks():
|
| 266 |
+
background_tasks = BackgroundTasks()
|
| 267 |
+
background_tasks.add_task(release_model_semaphore)
|
| 268 |
+
return background_tasks
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@app.post("/worker_generate")
|
| 273 |
+
async def api_generate(request: Request):
|
| 274 |
+
params = await request.json()
|
| 275 |
+
await acquire_model_semaphore()
|
| 276 |
+
output = worker.generate_gate(params)
|
| 277 |
+
release_model_semaphore()
|
| 278 |
+
return JSONResponse(output)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@app.post("/worker_get_status")
|
| 282 |
+
async def api_get_status(request: Request):
|
| 283 |
+
return worker.get_status()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@app.post("/model_details")
|
| 290 |
+
async def model_details(request: Request):
|
| 291 |
+
return {"context_length": worker.context_len}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
parser = argparse.ArgumentParser()
|
| 296 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 297 |
+
parser.add_argument("--port", type=int, default=23336)
|
| 298 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:23336")
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--model-path", type=str, default="Salesforce/blip2-opt-2.7b"
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
parser.add_argument(
|
| 308 |
+
"--model-names",
|
| 309 |
+
default="inpainting",
|
| 310 |
+
type=lambda s: s.split(","),
|
| 311 |
+
help="Optional display comma separated names",
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 314 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 315 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 316 |
+
parser.add_argument("--no-register", action="store_true")
|
| 317 |
+
args = parser.parse_args()
|
| 318 |
+
logger.info(f"args: {args}")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
worker = ModelWorker(
|
| 322 |
+
args.controller_address,
|
| 323 |
+
args.worker_address,
|
| 324 |
+
worker_id,
|
| 325 |
+
args.no_register,
|
| 326 |
+
args.model_path,
|
| 327 |
+
args.model_names,
|
| 328 |
+
args.device,
|
| 329 |
+
)
|
| 330 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/instructpix2pix_test_message.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
"prompt": "Hi AI! make them like a cat"
|
| 74 |
+
}
|
| 75 |
+
tic = time.time()
|
| 76 |
+
response = requests.post(
|
| 77 |
+
worker_addr + "/worker_generate",
|
| 78 |
+
headers=headers,
|
| 79 |
+
json=datas,
|
| 80 |
+
)
|
| 81 |
+
toc = time.time()
|
| 82 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 83 |
+
|
| 84 |
+
print("detection result:")
|
| 85 |
+
print(response.json())
|
| 86 |
+
res = response.json()
|
| 87 |
+
|
| 88 |
+
image = Image.open(BytesIO(base64.b64decode(res['edited_image']))).convert("RGB")
|
| 89 |
+
# save
|
| 90 |
+
image.save("demo2_edited2.jpg")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
parser = argparse.ArgumentParser()
|
| 99 |
+
# worker parameters
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument("--worker-address", type=str)
|
| 104 |
+
parser.add_argument("--model-name", type=str, default='ip2p')
|
| 105 |
+
|
| 106 |
+
# model parameters
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--image_path", type=str, default="78851692243550_.pic.jpg"
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--send_image", action="store_true",
|
| 112 |
+
)
|
| 113 |
+
args = parser.parse_args()
|
| 114 |
+
|
| 115 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/instructpix2pix_worker.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import asyncio
|
| 9 |
+
import dataclasses
|
| 10 |
+
import logging
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from typing import List, Tuple, Union
|
| 16 |
+
import threading
|
| 17 |
+
import uuid
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
import base64
|
| 21 |
+
|
| 22 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 23 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 24 |
+
import numpy as np
|
| 25 |
+
import requests
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 29 |
+
|
| 30 |
+
from groundingdino.util.inference import load_model, predict
|
| 31 |
+
import groundingdino.datasets.transforms as T
|
| 32 |
+
from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
from transformers import (
|
| 36 |
+
AutoTokenizer,
|
| 37 |
+
AutoModelForCausalLM,
|
| 38 |
+
LlamaTokenizer,
|
| 39 |
+
AutoModel,
|
| 40 |
+
)
|
| 41 |
+
except ImportError:
|
| 42 |
+
from transformers import (
|
| 43 |
+
AutoTokenizer,
|
| 44 |
+
AutoModelForCausalLM,
|
| 45 |
+
LLaMATokenizer,
|
| 46 |
+
AutoModel,
|
| 47 |
+
)
|
| 48 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 49 |
+
|
| 50 |
+
import torch
|
| 51 |
+
import torch.nn.functional as F
|
| 52 |
+
import uvicorn
|
| 53 |
+
|
| 54 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 55 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 56 |
+
|
| 57 |
+
GB = 1 << 30
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
now_file_name = os.__file__
|
| 61 |
+
logdir = "logs/workers/"
|
| 62 |
+
os.makedirs(logdir, exist_ok=True)
|
| 63 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 64 |
+
|
| 65 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 66 |
+
logger = build_logger(now_file_name, logfile)
|
| 67 |
+
global_counter = 0
|
| 68 |
+
|
| 69 |
+
model_semaphore = None
|
| 70 |
+
|
| 71 |
+
def encode(image: Image):
|
| 72 |
+
buffered = BytesIO()
|
| 73 |
+
image.save(buffered, format="JPEG")
|
| 74 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 75 |
+
return img_b64_str
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def heart_beat_worker(controller):
|
| 79 |
+
while True:
|
| 80 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 81 |
+
controller.send_heart_beat()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class ModelWorker:
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
controller_addr,
|
| 88 |
+
worker_addr,
|
| 89 |
+
worker_id,
|
| 90 |
+
no_register,
|
| 91 |
+
model_path,
|
| 92 |
+
model_names,
|
| 93 |
+
device,
|
| 94 |
+
):
|
| 95 |
+
self.controller_addr = controller_addr
|
| 96 |
+
self.worker_addr = worker_addr
|
| 97 |
+
self.worker_id = worker_id
|
| 98 |
+
self.model_names = model_names
|
| 99 |
+
self.device = device
|
| 100 |
+
|
| 101 |
+
# # load model
|
| 102 |
+
# logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 103 |
+
# self.processor = AutoProcessor.from_pretrained(model_path)
|
| 104 |
+
# self.model = Blip2ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16)
|
| 105 |
+
# self.model.eval()
|
| 106 |
+
# self.model.to(device)
|
| 107 |
+
model_id = "timbrooks/instruct-pix2pix"
|
| 108 |
+
pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
| 109 |
+
pipe.to("cuda")
|
| 110 |
+
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
| 111 |
+
|
| 112 |
+
self.pipe = pipe
|
| 113 |
+
|
| 114 |
+
if not no_register:
|
| 115 |
+
self.register_to_controller()
|
| 116 |
+
self.heart_beat_thread = threading.Thread(
|
| 117 |
+
target=heart_beat_worker, args=(self,)
|
| 118 |
+
)
|
| 119 |
+
self.heart_beat_thread.start()
|
| 120 |
+
|
| 121 |
+
def resize(self, image:Image, resize_w:int, resize_h:int):
|
| 122 |
+
image = image.resize((resize_w, resize_h))
|
| 123 |
+
return image
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def register_to_controller(self):
|
| 127 |
+
logger.info("Register to controller")
|
| 128 |
+
|
| 129 |
+
url = self.controller_addr + "/register_worker"
|
| 130 |
+
data = {
|
| 131 |
+
"worker_name": self.worker_addr,
|
| 132 |
+
"check_heart_beat": True,
|
| 133 |
+
"worker_status": self.get_status(),
|
| 134 |
+
}
|
| 135 |
+
r = requests.post(url, json=data)
|
| 136 |
+
assert r.status_code == 200
|
| 137 |
+
|
| 138 |
+
def send_heart_beat(self):
|
| 139 |
+
logger.info(
|
| 140 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 141 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 142 |
+
f"global_counter: {global_counter}. "
|
| 143 |
+
f"worker_id: {worker_id}. "
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 147 |
+
|
| 148 |
+
while True:
|
| 149 |
+
try:
|
| 150 |
+
ret = requests.post(
|
| 151 |
+
url,
|
| 152 |
+
json={
|
| 153 |
+
"worker_name": self.worker_addr,
|
| 154 |
+
"queue_length": self.get_queue_length(),
|
| 155 |
+
},
|
| 156 |
+
timeout=5,
|
| 157 |
+
)
|
| 158 |
+
exist = ret.json()["exist"]
|
| 159 |
+
break
|
| 160 |
+
except requests.exceptions.RequestException as e:
|
| 161 |
+
logger.error(f"heart beat error: {e}")
|
| 162 |
+
time.sleep(5)
|
| 163 |
+
|
| 164 |
+
if not exist:
|
| 165 |
+
self.register_to_controller()
|
| 166 |
+
|
| 167 |
+
def get_queue_length(self):
|
| 168 |
+
if (
|
| 169 |
+
model_semaphore is None
|
| 170 |
+
or model_semaphore._value is None
|
| 171 |
+
or model_semaphore._waiters is None
|
| 172 |
+
):
|
| 173 |
+
return 0
|
| 174 |
+
else:
|
| 175 |
+
return (
|
| 176 |
+
args.limit_model_concurrency
|
| 177 |
+
- model_semaphore._value
|
| 178 |
+
+ len(model_semaphore._waiters)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def get_status(self):
|
| 182 |
+
return {
|
| 183 |
+
"model_names": self.model_names,
|
| 184 |
+
"speed": 1,
|
| 185 |
+
"queue_length": self.get_queue_length(),
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if os.path.exists(image_path):
|
| 192 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 193 |
+
else:
|
| 194 |
+
# base64 coding
|
| 195 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 196 |
+
|
| 197 |
+
return image_source
|
| 198 |
+
|
| 199 |
+
def generate_stream_func(self, model, params, device):
|
| 200 |
+
# get inputs
|
| 201 |
+
image_path = params["image"]
|
| 202 |
+
prompt = params["prompt"]
|
| 203 |
+
|
| 204 |
+
# load image and run models
|
| 205 |
+
image = self.load_image(image_path)
|
| 206 |
+
|
| 207 |
+
# resize to 512, 512
|
| 208 |
+
w, h = image.size
|
| 209 |
+
image = self.resize(image, 512, 512)
|
| 210 |
+
|
| 211 |
+
# run
|
| 212 |
+
images = self.pipe(prompt, image=image, num_inference_steps=30, image_guidance_scale=1).images
|
| 213 |
+
image = images[0]
|
| 214 |
+
|
| 215 |
+
# re-resize
|
| 216 |
+
image = self.resize(image, w, h)
|
| 217 |
+
|
| 218 |
+
# save image
|
| 219 |
+
# images[0].save("test.jpg")
|
| 220 |
+
|
| 221 |
+
pred_dict = {
|
| 222 |
+
"edited_image": encode(image),
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
return pred_dict
|
| 226 |
+
|
| 227 |
+
def generate_gate(self, params):
|
| 228 |
+
try:
|
| 229 |
+
|
| 230 |
+
ret = {"text": "", "error_code": 0}
|
| 231 |
+
ret = self.generate_stream_func(
|
| 232 |
+
None,
|
| 233 |
+
params,
|
| 234 |
+
self.device,
|
| 235 |
+
)
|
| 236 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 237 |
+
ret = {
|
| 238 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 239 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 240 |
+
}
|
| 241 |
+
except (ValueError, RuntimeError) as e:
|
| 242 |
+
ret = {
|
| 243 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 244 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 245 |
+
}
|
| 246 |
+
return ret
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
app = FastAPI()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def release_model_semaphore():
|
| 254 |
+
model_semaphore.release()
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def acquire_model_semaphore():
|
| 258 |
+
global model_semaphore, global_counter
|
| 259 |
+
global_counter += 1
|
| 260 |
+
if model_semaphore is None:
|
| 261 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 262 |
+
return model_semaphore.acquire()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def create_background_tasks():
|
| 266 |
+
background_tasks = BackgroundTasks()
|
| 267 |
+
background_tasks.add_task(release_model_semaphore)
|
| 268 |
+
return background_tasks
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@app.post("/worker_generate")
|
| 273 |
+
async def api_generate(request: Request):
|
| 274 |
+
params = await request.json()
|
| 275 |
+
await acquire_model_semaphore()
|
| 276 |
+
output = worker.generate_gate(params)
|
| 277 |
+
release_model_semaphore()
|
| 278 |
+
return JSONResponse(output)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@app.post("/worker_get_status")
|
| 282 |
+
async def api_get_status(request: Request):
|
| 283 |
+
return worker.get_status()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@app.post("/model_details")
|
| 290 |
+
async def model_details(request: Request):
|
| 291 |
+
return {"context_length": worker.context_len}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
parser = argparse.ArgumentParser()
|
| 296 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 297 |
+
parser.add_argument("--port", type=int, default=21306)
|
| 298 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21306")
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--model-path", type=str, default="Salesforce/blip2-opt-2.7b"
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
parser.add_argument(
|
| 308 |
+
"--model-names",
|
| 309 |
+
default="instruct-pix2pix,ip2p",
|
| 310 |
+
type=lambda s: s.split(","),
|
| 311 |
+
help="Optional display comma separated names",
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 314 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 315 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 316 |
+
parser.add_argument("--no-register", action="store_true")
|
| 317 |
+
args = parser.parse_args()
|
| 318 |
+
logger.info(f"args: {args}")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
worker = ModelWorker(
|
| 322 |
+
args.controller_address,
|
| 323 |
+
args.worker_address,
|
| 324 |
+
worker_id,
|
| 325 |
+
args.no_register,
|
| 326 |
+
args.model_path,
|
| 327 |
+
args.model_names,
|
| 328 |
+
args.device,
|
| 329 |
+
)
|
| 330 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/ocr_test_message.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
}
|
| 74 |
+
tic = time.time()
|
| 75 |
+
response = requests.post(
|
| 76 |
+
worker_addr + "/worker_generate",
|
| 77 |
+
headers=headers,
|
| 78 |
+
json=datas,
|
| 79 |
+
)
|
| 80 |
+
toc = time.time()
|
| 81 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 82 |
+
|
| 83 |
+
print("detection result:")
|
| 84 |
+
print(response.json())
|
| 85 |
+
# response is 'Response' with :
|
| 86 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
parser = argparse.ArgumentParser()
|
| 93 |
+
# worker parameters
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--worker-address", type=str)
|
| 98 |
+
parser.add_argument("--model-name", type=str, default='ocr')
|
| 99 |
+
|
| 100 |
+
# model parameters
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--image_path", type=str, default='/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/grounded_sam2.png'
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--send_image", action="store_true",
|
| 106 |
+
)
|
| 107 |
+
args = parser.parse_args()
|
| 108 |
+
|
| 109 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/ocr_worker.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
from functools import partial
|
| 5 |
+
import sys, os
|
| 6 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import asyncio
|
| 10 |
+
import dataclasses
|
| 11 |
+
import logging
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
from typing import List, Tuple, Union
|
| 17 |
+
import threading
|
| 18 |
+
import uuid
|
| 19 |
+
|
| 20 |
+
from io import BytesIO
|
| 21 |
+
import base64
|
| 22 |
+
|
| 23 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 24 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 25 |
+
import numpy as np
|
| 26 |
+
import requests
|
| 27 |
+
from PIL import Image
|
| 28 |
+
import easyocr
|
| 29 |
+
|
| 30 |
+
sys.path.append('Tag2Text')
|
| 31 |
+
from Tag2Text.models import tag2text
|
| 32 |
+
from Tag2Text import inference_ram
|
| 33 |
+
import torchvision.transforms as TS
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from transformers import (
|
| 37 |
+
AutoTokenizer,
|
| 38 |
+
AutoModelForCausalLM,
|
| 39 |
+
LlamaTokenizer,
|
| 40 |
+
AutoModel,
|
| 41 |
+
)
|
| 42 |
+
except ImportError:
|
| 43 |
+
from transformers import (
|
| 44 |
+
AutoTokenizer,
|
| 45 |
+
AutoModelForCausalLM,
|
| 46 |
+
LLaMATokenizer,
|
| 47 |
+
AutoModel,
|
| 48 |
+
)
|
| 49 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn.functional as F
|
| 53 |
+
import uvicorn
|
| 54 |
+
|
| 55 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 56 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 57 |
+
|
| 58 |
+
GB = 1 << 30
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
now_file_name = os.__file__
|
| 62 |
+
logdir = "logs/workers/"
|
| 63 |
+
os.makedirs(logdir, exist_ok=True)
|
| 64 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 65 |
+
|
| 66 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 67 |
+
logger = build_logger(now_file_name, logfile)
|
| 68 |
+
global_counter = 0
|
| 69 |
+
|
| 70 |
+
model_semaphore = None
|
| 71 |
+
|
| 72 |
+
R = partial(round, ndigits=2)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def heart_beat_worker(controller):
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 78 |
+
controller.send_heart_beat()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelWorker:
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
controller_addr,
|
| 85 |
+
worker_addr,
|
| 86 |
+
worker_id,
|
| 87 |
+
no_register,
|
| 88 |
+
model_path,
|
| 89 |
+
model_names,
|
| 90 |
+
device,
|
| 91 |
+
):
|
| 92 |
+
self.controller_addr = controller_addr
|
| 93 |
+
self.worker_addr = worker_addr
|
| 94 |
+
self.worker_id = worker_id
|
| 95 |
+
self.model_names = model_names
|
| 96 |
+
self.device = device
|
| 97 |
+
|
| 98 |
+
# load model
|
| 99 |
+
self.ocr_model = easyocr.Reader(['ch_sim','en'])
|
| 100 |
+
|
| 101 |
+
if not no_register:
|
| 102 |
+
self.register_to_controller()
|
| 103 |
+
self.heart_beat_thread = threading.Thread(
|
| 104 |
+
target=heart_beat_worker, args=(self,)
|
| 105 |
+
)
|
| 106 |
+
self.heart_beat_thread.start()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def register_to_controller(self):
|
| 111 |
+
logger.info("Register to controller")
|
| 112 |
+
|
| 113 |
+
url = self.controller_addr + "/register_worker"
|
| 114 |
+
data = {
|
| 115 |
+
"worker_name": self.worker_addr,
|
| 116 |
+
"check_heart_beat": True,
|
| 117 |
+
"worker_status": self.get_status(),
|
| 118 |
+
}
|
| 119 |
+
r = requests.post(url, json=data)
|
| 120 |
+
assert r.status_code == 200
|
| 121 |
+
|
| 122 |
+
def send_heart_beat(self):
|
| 123 |
+
logger.info(
|
| 124 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 125 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 126 |
+
f"global_counter: {global_counter}. "
|
| 127 |
+
f"worker_id: {worker_id}. "
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 131 |
+
|
| 132 |
+
while True:
|
| 133 |
+
try:
|
| 134 |
+
ret = requests.post(
|
| 135 |
+
url,
|
| 136 |
+
json={
|
| 137 |
+
"worker_name": self.worker_addr,
|
| 138 |
+
"queue_length": self.get_queue_length(),
|
| 139 |
+
},
|
| 140 |
+
timeout=5,
|
| 141 |
+
)
|
| 142 |
+
exist = ret.json()["exist"]
|
| 143 |
+
break
|
| 144 |
+
except requests.exceptions.RequestException as e:
|
| 145 |
+
logger.error(f"heart beat error: {e}")
|
| 146 |
+
time.sleep(5)
|
| 147 |
+
|
| 148 |
+
if not exist:
|
| 149 |
+
self.register_to_controller()
|
| 150 |
+
|
| 151 |
+
def get_queue_length(self):
|
| 152 |
+
if (
|
| 153 |
+
model_semaphore is None
|
| 154 |
+
or model_semaphore._value is None
|
| 155 |
+
or model_semaphore._waiters is None
|
| 156 |
+
):
|
| 157 |
+
return 0
|
| 158 |
+
else:
|
| 159 |
+
return (
|
| 160 |
+
args.limit_model_concurrency
|
| 161 |
+
- model_semaphore._value
|
| 162 |
+
+ len(model_semaphore._waiters)
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def get_status(self):
|
| 166 |
+
return {
|
| 167 |
+
"model_names": self.model_names,
|
| 168 |
+
"speed": 1,
|
| 169 |
+
"queue_length": self.get_queue_length(),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 173 |
+
|
| 174 |
+
if os.path.exists(image_path):
|
| 175 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 176 |
+
else:
|
| 177 |
+
# base64 coding
|
| 178 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 179 |
+
return image_source
|
| 180 |
+
|
| 181 |
+
def generate_stream_func(self, model, params, device):
|
| 182 |
+
# get inputs
|
| 183 |
+
image_path = params["image"]
|
| 184 |
+
|
| 185 |
+
# load image and run models
|
| 186 |
+
image = self.load_image(image_path)
|
| 187 |
+
|
| 188 |
+
# tagging:
|
| 189 |
+
result = self.ocr_model.readtext(np.array(image))
|
| 190 |
+
|
| 191 |
+
boxes = [i[0] for i in result]
|
| 192 |
+
# int 64 -> int
|
| 193 |
+
# boxes = [[[int(ib[0]), int(ib[1])]for ib in box] for box in boxes]
|
| 194 |
+
# [[x1y1, x2y1, x2y2, x1y2]] -> [x1, y1, x2, y2]
|
| 195 |
+
boxes = [[int(box[0][0]), int(box[0][1]), int(box[2][0]), int(box[2][1])] for box in boxes]
|
| 196 |
+
# w, h
|
| 197 |
+
w, h = image.size
|
| 198 |
+
boxes = [[R(box[0] / w), R(box[1] / h), R(box[2] / w), R(box[3] / h)] for box in boxes]
|
| 199 |
+
|
| 200 |
+
pred_dict = {
|
| 201 |
+
"boxes": boxes,
|
| 202 |
+
"texts": [i[1] for i in result],
|
| 203 |
+
"scores": [R(i[2]) for i in result], # H,W
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
return pred_dict
|
| 207 |
+
|
| 208 |
+
def generate_gate(self, params):
|
| 209 |
+
try:
|
| 210 |
+
|
| 211 |
+
ret = {"text": "", "error_code": 0}
|
| 212 |
+
ret = self.generate_stream_func(
|
| 213 |
+
None,
|
| 214 |
+
params,
|
| 215 |
+
self.device,
|
| 216 |
+
)
|
| 217 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 218 |
+
ret = {
|
| 219 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 220 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 221 |
+
}
|
| 222 |
+
except (ValueError, RuntimeError) as e:
|
| 223 |
+
ret = {
|
| 224 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 225 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 226 |
+
}
|
| 227 |
+
return ret
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
app = FastAPI()
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def release_model_semaphore():
|
| 234 |
+
model_semaphore.release()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def acquire_model_semaphore():
|
| 238 |
+
global model_semaphore, global_counter
|
| 239 |
+
global_counter += 1
|
| 240 |
+
if model_semaphore is None:
|
| 241 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 242 |
+
return model_semaphore.acquire()
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def create_background_tasks():
|
| 246 |
+
background_tasks = BackgroundTasks()
|
| 247 |
+
background_tasks.add_task(release_model_semaphore)
|
| 248 |
+
return background_tasks
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@app.post("/worker_generate")
|
| 253 |
+
async def api_generate(request: Request):
|
| 254 |
+
params = await request.json()
|
| 255 |
+
await acquire_model_semaphore()
|
| 256 |
+
output = worker.generate_gate(params)
|
| 257 |
+
release_model_semaphore()
|
| 258 |
+
return JSONResponse(output)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@app.post("/worker_get_status")
|
| 262 |
+
async def api_get_status(request: Request):
|
| 263 |
+
return worker.get_status()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@app.post("/model_details")
|
| 270 |
+
async def model_details(request: Request):
|
| 271 |
+
return {"context_length": worker.context_len}
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
if __name__ == "__main__":
|
| 275 |
+
parser = argparse.ArgumentParser()
|
| 276 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 277 |
+
parser.add_argument("--port", type=int, default=21029)
|
| 278 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21029")
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--model-path", type=str, default=""
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--model-names",
|
| 289 |
+
default="ocr,easyocr",
|
| 290 |
+
type=lambda s: s.split(","),
|
| 291 |
+
help="Optional display comma separated names",
|
| 292 |
+
)
|
| 293 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 294 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 295 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 296 |
+
parser.add_argument("--no-register", action="store_true")
|
| 297 |
+
args = parser.parse_args()
|
| 298 |
+
logger.info(f"args: {args}")
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
worker = ModelWorker(
|
| 302 |
+
args.controller_address,
|
| 303 |
+
args.worker_address,
|
| 304 |
+
worker_id,
|
| 305 |
+
args.no_register,
|
| 306 |
+
args.model_path,
|
| 307 |
+
args.model_names,
|
| 308 |
+
args.device,
|
| 309 |
+
)
|
| 310 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_test_message.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import time
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
import io
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
import requests
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import base64
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torchvision.transforms.functional as F
|
| 15 |
+
|
| 16 |
+
def load_image(image_path):
|
| 17 |
+
img = Image.open(image_path).convert('RGB')
|
| 18 |
+
# import ipdb; ipdb.set_trace()
|
| 19 |
+
# resize if needed
|
| 20 |
+
w, h = img.size
|
| 21 |
+
if max(h, w) > 800:
|
| 22 |
+
if h > w:
|
| 23 |
+
new_h = 800
|
| 24 |
+
new_w = int(w * 800 / h)
|
| 25 |
+
else:
|
| 26 |
+
new_w = 800
|
| 27 |
+
new_h = int(h * 800 / w)
|
| 28 |
+
# import ipdb; ipdb.set_trace()
|
| 29 |
+
img = F.resize(img, (new_h, new_w))
|
| 30 |
+
return img
|
| 31 |
+
|
| 32 |
+
def encode(image: Image):
|
| 33 |
+
buffered = BytesIO()
|
| 34 |
+
image.save(buffered, format="JPEG")
|
| 35 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 36 |
+
return img_b64_str
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
model_name = args.model_name
|
| 41 |
+
|
| 42 |
+
if args.worker_address:
|
| 43 |
+
worker_addr = args.worker_address
|
| 44 |
+
else:
|
| 45 |
+
controller_addr = args.controller_address
|
| 46 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 47 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 48 |
+
models = ret.json()["models"]
|
| 49 |
+
models.sort()
|
| 50 |
+
print(f"Models: {models}")
|
| 51 |
+
|
| 52 |
+
ret = requests.post(
|
| 53 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 54 |
+
)
|
| 55 |
+
worker_addr = ret.json()["address"]
|
| 56 |
+
print(f"worker_addr: {worker_addr}")
|
| 57 |
+
|
| 58 |
+
if worker_addr == "":
|
| 59 |
+
print(f"No available workers for {model_name}")
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 63 |
+
img_arg = args.image_path
|
| 64 |
+
image = load_image(img_arg).convert('RGB')
|
| 65 |
+
image_data = io.BytesIO()
|
| 66 |
+
image.save(image_data, format='JPEG')
|
| 67 |
+
image_data_bytes = image_data.getvalue()
|
| 68 |
+
# 将图像数据编码为Base64字符串
|
| 69 |
+
encoded_image = base64.b64encode(image_data_bytes).decode('utf-8')
|
| 70 |
+
mode=args.mode
|
| 71 |
+
datas = {
|
| 72 |
+
"caption": args.caption,
|
| 73 |
+
"image": encoded_image,
|
| 74 |
+
"mask":None,
|
| 75 |
+
"mode":mode
|
| 76 |
+
}
|
| 77 |
+
tic = time.time()
|
| 78 |
+
response = requests.post(
|
| 79 |
+
worker_addr + "/worker_generate",
|
| 80 |
+
headers=headers,
|
| 81 |
+
json=datas,
|
| 82 |
+
)
|
| 83 |
+
toc = time.time()
|
| 84 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 85 |
+
|
| 86 |
+
print("detection result:")
|
| 87 |
+
print(response.json())
|
| 88 |
+
# response is 'Response' with :
|
| 89 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 90 |
+
|
| 91 |
+
# visualize
|
| 92 |
+
res = response.json()
|
| 93 |
+
image_seg = res["image_seg"]
|
| 94 |
+
image_result = res["image"]
|
| 95 |
+
if image_seg is not None:
|
| 96 |
+
image_seg=Image.open(io.BytesIO(base64.b64decode(image_seg))).convert("RGB")
|
| 97 |
+
image_seg.save("output/seg.jpg")
|
| 98 |
+
if image_seg is not None:
|
| 99 |
+
image_result=Image.open(io.BytesIO(base64.b64decode(image_result))).convert("RGB")
|
| 100 |
+
image_result.save("output/result.jpg")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
parser = argparse.ArgumentParser()
|
| 105 |
+
# worker parameters
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:22003")
|
| 110 |
+
parser.add_argument("--model-name", type=str, default='grounding_dino')
|
| 111 |
+
parser.add_argument("--mode", type=str, default='openseed')
|
| 112 |
+
# parser.add_argument("--model-name", type=str, default='grounding_dino')
|
| 113 |
+
|
| 114 |
+
# model parameters
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--caption", type=str, default="house"
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--image_path", type=str, default="house.png"
|
| 120 |
+
)
|
| 121 |
+
args = parser.parse_args()
|
| 122 |
+
|
| 123 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_worker.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import numpy as np
|
| 5 |
+
np.random.seed(1)
|
| 6 |
+
import sys, os, io
|
| 7 |
+
# import pdb;pdb.set_trace()
|
| 8 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 9 |
+
import torch
|
| 10 |
+
from torchvision import transforms
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
from detectron2.data import MetadataCatalog
|
| 14 |
+
from detectron2.utils.colormap import random_color
|
| 15 |
+
from openseed.BaseModel import BaseModel
|
| 16 |
+
from openseed import build_model
|
| 17 |
+
from utils.arguments import load_opt_from_config_files
|
| 18 |
+
import argparse
|
| 19 |
+
import asyncio
|
| 20 |
+
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
import threading
|
| 24 |
+
import uuid
|
| 25 |
+
import base64
|
| 26 |
+
|
| 27 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 28 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 29 |
+
import requests
|
| 30 |
+
|
| 31 |
+
import torch.nn.functional as F
|
| 32 |
+
import uvicorn
|
| 33 |
+
|
| 34 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 35 |
+
from serve.utils_ import build_logger, pretty_print_semaphore
|
| 36 |
+
|
| 37 |
+
from PIL import Image
|
| 38 |
+
import numpy as np
|
| 39 |
+
import torch
|
| 40 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
|
| 41 |
+
from diffusers.utils import load_image
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
ade20k_classes=['wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed', 'window ', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp', 'tub', 'rail', 'cushion', 'base', 'box', 'column', 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path', 'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door', 'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove', 'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar', 'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', 'chandelier', 'awning', 'street lamp', 'booth', 'tv', 'plane', 'dirt track', 'clothes', 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van', 'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything', 'pool', 'stool', 'barrel', 'basket', 'falls', 'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake', 'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce', 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'pier', 'crt screen', 'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', 'clock', 'flag']
|
| 45 |
+
palette = np.asarray([
|
| 46 |
+
[0, 0, 0],
|
| 47 |
+
[120, 120, 120],
|
| 48 |
+
[180, 120, 120],
|
| 49 |
+
[6, 230, 230],
|
| 50 |
+
[80, 50, 50],
|
| 51 |
+
[4, 200, 3],
|
| 52 |
+
[120, 120, 80],
|
| 53 |
+
[140, 140, 140],
|
| 54 |
+
[204, 5, 255],
|
| 55 |
+
[230, 230, 230],
|
| 56 |
+
[4, 250, 7],
|
| 57 |
+
[224, 5, 255],
|
| 58 |
+
[235, 255, 7],
|
| 59 |
+
[150, 5, 61],
|
| 60 |
+
[120, 120, 70],
|
| 61 |
+
[8, 255, 51],
|
| 62 |
+
[255, 6, 82],
|
| 63 |
+
[143, 255, 140],
|
| 64 |
+
[204, 255, 4],
|
| 65 |
+
[255, 51, 7],
|
| 66 |
+
[204, 70, 3],
|
| 67 |
+
[0, 102, 200],
|
| 68 |
+
[61, 230, 250],
|
| 69 |
+
[255, 6, 51],
|
| 70 |
+
[11, 102, 255],
|
| 71 |
+
[255, 7, 71],
|
| 72 |
+
[255, 9, 224],
|
| 73 |
+
[9, 7, 230],
|
| 74 |
+
[220, 220, 220],
|
| 75 |
+
[255, 9, 92],
|
| 76 |
+
[112, 9, 255],
|
| 77 |
+
[8, 255, 214],
|
| 78 |
+
[7, 255, 224],
|
| 79 |
+
[255, 184, 6],
|
| 80 |
+
[10, 255, 71],
|
| 81 |
+
[255, 41, 10],
|
| 82 |
+
[7, 255, 255],
|
| 83 |
+
[224, 255, 8],
|
| 84 |
+
[102, 8, 255],
|
| 85 |
+
[255, 61, 6],
|
| 86 |
+
[255, 194, 7],
|
| 87 |
+
[255, 122, 8],
|
| 88 |
+
[0, 255, 20],
|
| 89 |
+
[255, 8, 41],
|
| 90 |
+
[255, 5, 153],
|
| 91 |
+
[6, 51, 255],
|
| 92 |
+
[235, 12, 255],
|
| 93 |
+
[160, 150, 20],
|
| 94 |
+
[0, 163, 255],
|
| 95 |
+
[140, 140, 140],
|
| 96 |
+
[250, 10, 15],
|
| 97 |
+
[20, 255, 0],
|
| 98 |
+
[31, 255, 0],
|
| 99 |
+
[255, 31, 0],
|
| 100 |
+
[255, 224, 0],
|
| 101 |
+
[153, 255, 0],
|
| 102 |
+
[0, 0, 255],
|
| 103 |
+
[255, 71, 0],
|
| 104 |
+
[0, 235, 255],
|
| 105 |
+
[0, 173, 255],
|
| 106 |
+
[31, 0, 255],
|
| 107 |
+
[11, 200, 200],
|
| 108 |
+
[255, 82, 0],
|
| 109 |
+
[0, 255, 245],
|
| 110 |
+
[0, 61, 255],
|
| 111 |
+
[0, 255, 112],
|
| 112 |
+
[0, 255, 133],
|
| 113 |
+
[255, 0, 0],
|
| 114 |
+
[255, 163, 0],
|
| 115 |
+
[255, 102, 0],
|
| 116 |
+
[194, 255, 0],
|
| 117 |
+
[0, 143, 255],
|
| 118 |
+
[51, 255, 0],
|
| 119 |
+
[0, 82, 255],
|
| 120 |
+
[0, 255, 41],
|
| 121 |
+
[0, 255, 173],
|
| 122 |
+
[10, 0, 255],
|
| 123 |
+
[173, 255, 0],
|
| 124 |
+
[0, 255, 153],
|
| 125 |
+
[255, 92, 0],
|
| 126 |
+
[255, 0, 255],
|
| 127 |
+
[255, 0, 245],
|
| 128 |
+
[255, 0, 102],
|
| 129 |
+
[255, 173, 0],
|
| 130 |
+
[255, 0, 20],
|
| 131 |
+
[255, 184, 184],
|
| 132 |
+
[0, 31, 255],
|
| 133 |
+
[0, 255, 61],
|
| 134 |
+
[0, 71, 255],
|
| 135 |
+
[255, 0, 204],
|
| 136 |
+
[0, 255, 194],
|
| 137 |
+
[0, 255, 82],
|
| 138 |
+
[0, 10, 255],
|
| 139 |
+
[0, 112, 255],
|
| 140 |
+
[51, 0, 255],
|
| 141 |
+
[0, 194, 255],
|
| 142 |
+
[0, 122, 255],
|
| 143 |
+
[0, 255, 163],
|
| 144 |
+
[255, 153, 0],
|
| 145 |
+
[0, 255, 10],
|
| 146 |
+
[255, 112, 0],
|
| 147 |
+
[143, 255, 0],
|
| 148 |
+
[82, 0, 255],
|
| 149 |
+
[163, 255, 0],
|
| 150 |
+
[255, 235, 0],
|
| 151 |
+
[8, 184, 170],
|
| 152 |
+
[133, 0, 255],
|
| 153 |
+
[0, 255, 92],
|
| 154 |
+
[184, 0, 255],
|
| 155 |
+
[255, 0, 31],
|
| 156 |
+
[0, 184, 255],
|
| 157 |
+
[0, 214, 255],
|
| 158 |
+
[255, 0, 112],
|
| 159 |
+
[92, 255, 0],
|
| 160 |
+
[0, 224, 255],
|
| 161 |
+
[112, 224, 255],
|
| 162 |
+
[70, 184, 160],
|
| 163 |
+
[163, 0, 255],
|
| 164 |
+
[153, 0, 255],
|
| 165 |
+
[71, 255, 0],
|
| 166 |
+
[255, 0, 163],
|
| 167 |
+
[255, 204, 0],
|
| 168 |
+
[255, 0, 143],
|
| 169 |
+
[0, 255, 235],
|
| 170 |
+
[133, 255, 0],
|
| 171 |
+
[255, 0, 235],
|
| 172 |
+
[245, 0, 255],
|
| 173 |
+
[255, 0, 122],
|
| 174 |
+
[255, 245, 0],
|
| 175 |
+
[10, 190, 212],
|
| 176 |
+
[214, 255, 0],
|
| 177 |
+
[0, 204, 255],
|
| 178 |
+
[20, 0, 255],
|
| 179 |
+
[255, 255, 0],
|
| 180 |
+
[0, 153, 255],
|
| 181 |
+
[0, 41, 255],
|
| 182 |
+
[0, 255, 204],
|
| 183 |
+
[41, 0, 255],
|
| 184 |
+
[41, 255, 0],
|
| 185 |
+
[173, 0, 255],
|
| 186 |
+
[0, 245, 255],
|
| 187 |
+
[71, 0, 255],
|
| 188 |
+
[122, 0, 255],
|
| 189 |
+
[0, 255, 184],
|
| 190 |
+
[0, 92, 255],
|
| 191 |
+
[184, 255, 0],
|
| 192 |
+
[0, 133, 255],
|
| 193 |
+
[255, 214, 0],
|
| 194 |
+
[25, 194, 194],
|
| 195 |
+
[102, 255, 0],
|
| 196 |
+
[92, 0, 255],
|
| 197 |
+
])
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
GB = 1 << 30
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
now_file_name = os.__file__
|
| 205 |
+
logdir = "logs/workers/"
|
| 206 |
+
os.makedirs(logdir, exist_ok=True)
|
| 207 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 208 |
+
|
| 209 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 210 |
+
logger = build_logger(now_file_name, logfile)
|
| 211 |
+
global_counter = 0
|
| 212 |
+
|
| 213 |
+
model_semaphore = None
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def heart_beat_worker(controller):
|
| 217 |
+
while True:
|
| 218 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 219 |
+
controller.send_heart_beat()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
conf_files="configs/openseed/openseed_swinl_lang_decouple.yaml"
|
| 223 |
+
pretrained_pth="/path/to/openseed_ade20k_swinl.pt"
|
| 224 |
+
class ModelWorker:
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
controller_addr,
|
| 228 |
+
worker_addr,
|
| 229 |
+
worker_id,
|
| 230 |
+
model_names,
|
| 231 |
+
):
|
| 232 |
+
self.controller_addr = controller_addr
|
| 233 |
+
self.worker_addr = worker_addr
|
| 234 |
+
self.worker_id = worker_id
|
| 235 |
+
self.model_names = model_names
|
| 236 |
+
|
| 237 |
+
# self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
|
| 238 |
+
# self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
|
| 239 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
| 240 |
+
"lllyasviel/sd-controlnet-seg", torch_dtype=torch.float32
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 244 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float32
|
| 245 |
+
)
|
| 246 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
| 247 |
+
self.register_to_controller()
|
| 248 |
+
self.heart_beat_thread = threading.Thread(
|
| 249 |
+
target=heart_beat_worker, args=(self,)
|
| 250 |
+
)
|
| 251 |
+
self.heart_beat_thread.start()
|
| 252 |
+
opt = load_opt_from_config_files([conf_files])
|
| 253 |
+
# if cmdline_args.user_dir:
|
| 254 |
+
# absolute_user_dir = os.path.abspath(cmdline_args.user_dir)
|
| 255 |
+
# opt['user_dir'] = absolute_user_dir
|
| 256 |
+
|
| 257 |
+
# META DATA
|
| 258 |
+
# pretrained_pth = os.path.join(opt['WEIGHT'])
|
| 259 |
+
# output_root = './output'
|
| 260 |
+
# image_pth = 'images/animals.png'
|
| 261 |
+
|
| 262 |
+
self.openseed_model = BaseModel(opt, build_model(opt)).from_pretrained(pretrained_pth).eval().cuda()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def register_to_controller(self):
|
| 266 |
+
logger.info("Register to controller")
|
| 267 |
+
|
| 268 |
+
url = self.controller_addr + "/register_worker"
|
| 269 |
+
data = {
|
| 270 |
+
"worker_name": self.worker_addr,
|
| 271 |
+
"check_heart_beat": True,
|
| 272 |
+
"worker_status": self.get_status(),
|
| 273 |
+
}
|
| 274 |
+
r = requests.post(url, json=data)
|
| 275 |
+
assert r.status_code == 200
|
| 276 |
+
|
| 277 |
+
def send_heart_beat(self):
|
| 278 |
+
logger.info(
|
| 279 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 280 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 281 |
+
f"global_counter: {global_counter}. "
|
| 282 |
+
f"worker_id: {worker_id}. "
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 286 |
+
|
| 287 |
+
while True:
|
| 288 |
+
try:
|
| 289 |
+
ret = requests.post(
|
| 290 |
+
url,
|
| 291 |
+
json={
|
| 292 |
+
"worker_name": self.worker_addr,
|
| 293 |
+
"queue_length": self.get_queue_length(),
|
| 294 |
+
},
|
| 295 |
+
timeout=5,
|
| 296 |
+
)
|
| 297 |
+
exist = ret.json()["exist"]
|
| 298 |
+
break
|
| 299 |
+
except requests.exceptions.RequestException as e:
|
| 300 |
+
logger.error(f"heart beat error: {e}")
|
| 301 |
+
time.sleep(5)
|
| 302 |
+
|
| 303 |
+
if not exist:
|
| 304 |
+
self.register_to_controller()
|
| 305 |
+
|
| 306 |
+
def get_queue_length(self):
|
| 307 |
+
if (
|
| 308 |
+
model_semaphore is None
|
| 309 |
+
or model_semaphore._value is None
|
| 310 |
+
or model_semaphore._waiters is None
|
| 311 |
+
):
|
| 312 |
+
return 0
|
| 313 |
+
else:
|
| 314 |
+
return (
|
| 315 |
+
args.limit_model_concurrency
|
| 316 |
+
- model_semaphore._value
|
| 317 |
+
+ len(model_semaphore._waiters)
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def get_status(self):
|
| 321 |
+
return {
|
| 322 |
+
"model_names": self.model_names,
|
| 323 |
+
"speed": 1,
|
| 324 |
+
"queue_length": self.get_queue_length(),
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def generate_stream_func(self, params ):
|
| 329 |
+
# get inputs
|
| 330 |
+
image_b64 = params["image"]
|
| 331 |
+
mode = params["mode"]
|
| 332 |
+
if mode=="openseed":
|
| 333 |
+
t = []
|
| 334 |
+
t.append(transforms.Resize(512, interpolation=Image.BICUBIC))
|
| 335 |
+
transform = transforms.Compose(t)
|
| 336 |
+
|
| 337 |
+
stuff_classes = ade20k_classes
|
| 338 |
+
stuff_colors = [random_color(rgb=True, maximum=255).astype(np.int).tolist() for _ in
|
| 339 |
+
range(len(stuff_classes))]
|
| 340 |
+
stuff_dataset_id_to_contiguous_id = {x: x for x in range(len(stuff_classes))}
|
| 341 |
+
|
| 342 |
+
MetadataCatalog.get("demo").set(
|
| 343 |
+
stuff_colors=stuff_colors,
|
| 344 |
+
stuff_dataset_id_to_contiguous_id=stuff_dataset_id_to_contiguous_id,
|
| 345 |
+
)
|
| 346 |
+
model=self.openseed_model
|
| 347 |
+
model.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(stuff_classes, is_eval=True)
|
| 348 |
+
metadata = MetadataCatalog.get('inference')
|
| 349 |
+
model.model.metadata = metadata
|
| 350 |
+
model.model.sem_seg_head.num_classes = len(stuff_classes)
|
| 351 |
+
with torch.no_grad():
|
| 352 |
+
image_ori = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")
|
| 353 |
+
width = image_ori.size[0]
|
| 354 |
+
height = image_ori.size[1]
|
| 355 |
+
image = transform(image_ori)
|
| 356 |
+
image = np.asarray(image)
|
| 357 |
+
images = torch.from_numpy(image.copy()).permute(2, 0, 1).cuda()
|
| 358 |
+
|
| 359 |
+
batch_inputs = [{'image': images, 'height': height, 'width': width}]
|
| 360 |
+
outputs = model.forward(batch_inputs, inference_task="sem_seg")
|
| 361 |
+
# outputs[-1]['sem_seg'] = F.interpolate(outputs[-1]['sem_seg'][None], size=(512, 512), mode='bilinear',
|
| 362 |
+
# align_corners=False)[0].cpu()
|
| 363 |
+
seg = outputs[-1]['sem_seg'].max(0)[1].cpu()
|
| 364 |
+
|
| 365 |
+
#seg: 512x512 (0~149)
|
| 366 |
+
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
|
| 367 |
+
|
| 368 |
+
for label, color in enumerate(palette):
|
| 369 |
+
color_seg[seg == label, :] = color
|
| 370 |
+
|
| 371 |
+
color_seg = color_seg.astype(np.uint8)
|
| 372 |
+
|
| 373 |
+
image = Image.fromarray(color_seg)
|
| 374 |
+
image_data = io.BytesIO()
|
| 375 |
+
image.save(image_data, format='JPEG')
|
| 376 |
+
image_data_bytes = image_data.getvalue()
|
| 377 |
+
# 将图像数据编码为Base64字符串
|
| 378 |
+
encoded_image = base64.b64encode(image_data_bytes).decode('utf-8')
|
| 379 |
+
pred_dict = {
|
| 380 |
+
"image_seg": encoded_image,
|
| 381 |
+
}
|
| 382 |
+
else:
|
| 383 |
+
assert mode=="controlnet"
|
| 384 |
+
text_prompt = params["prompt"]["caption"]
|
| 385 |
+
image=params['mask']
|
| 386 |
+
image = Image.open(io.BytesIO(base64.b64decode(image))).convert("RGB")
|
| 387 |
+
image1 = self.pipe(text_prompt, image, num_inference_steps=20).images[0]
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
image_data1 = io.BytesIO()
|
| 391 |
+
image1.save(image_data1, format='JPEG')
|
| 392 |
+
image_data_bytes1 = image_data1.getvalue()
|
| 393 |
+
# 将图像数据编码为Base64字符串
|
| 394 |
+
encoded_image1 = base64.b64encode(image_data_bytes1).decode('utf-8')
|
| 395 |
+
|
| 396 |
+
pred_dict = {
|
| 397 |
+
"edited_image": encoded_image1,
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
return pred_dict
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def generate_gate(self, params):
|
| 404 |
+
try:
|
| 405 |
+
|
| 406 |
+
ret = {"text": "", "error_code": 0}
|
| 407 |
+
ret = self.generate_stream_func(
|
| 408 |
+
params
|
| 409 |
+
)
|
| 410 |
+
except (ValueError, RuntimeError) as e:
|
| 411 |
+
ret = {
|
| 412 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 413 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 414 |
+
}
|
| 415 |
+
return ret
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
app = FastAPI()
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def release_model_semaphore():
|
| 422 |
+
model_semaphore.release()
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def acquire_model_semaphore():
|
| 426 |
+
global model_semaphore, global_counter
|
| 427 |
+
global_counter += 1
|
| 428 |
+
if model_semaphore is None:
|
| 429 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 430 |
+
return model_semaphore.acquire()
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def create_background_tasks():
|
| 434 |
+
background_tasks = BackgroundTasks()
|
| 435 |
+
background_tasks.add_task(release_model_semaphore)
|
| 436 |
+
return background_tasks
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@app.post("/worker_generate")
|
| 441 |
+
async def api_generate(request: Request):
|
| 442 |
+
params = await request.json()
|
| 443 |
+
await acquire_model_semaphore()
|
| 444 |
+
output = worker.generate_gate(params)
|
| 445 |
+
release_model_semaphore()
|
| 446 |
+
return JSONResponse(output)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@app.post("/worker_get_status")
|
| 450 |
+
async def api_get_status(request: Request):
|
| 451 |
+
return worker.get_status()
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
@app.post("/model_details")
|
| 458 |
+
async def model_details(request: Request):
|
| 459 |
+
return {"context_length": worker.context_len}
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
parser = argparse.ArgumentParser()
|
| 464 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 465 |
+
parser.add_argument("--port", type=int, default=22003)
|
| 466 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:22003")
|
| 467 |
+
parser.add_argument(
|
| 468 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
parser.add_argument(
|
| 472 |
+
"--model-names",
|
| 473 |
+
default="controlnet",
|
| 474 |
+
type=lambda s: s.split(","),
|
| 475 |
+
help="Optional display comma separated names",
|
| 476 |
+
)
|
| 477 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 478 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 479 |
+
parser.add_argument("--no-register", action="store_true")
|
| 480 |
+
args = parser.parse_args()
|
| 481 |
+
logger.info(f"args: {args}")
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
worker = ModelWorker(
|
| 485 |
+
args.controller_address,
|
| 486 |
+
args.worker_address,
|
| 487 |
+
worker_id,
|
| 488 |
+
args.model_names
|
| 489 |
+
)
|
| 490 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/openseed_controlnet_worker_readme.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OpenSeeD and ControlNet Worker
|
| 2 |
+
## Install
|
| 3 |
+
```sh
|
| 4 |
+
git clone https://github.com/IDEA-Research/OpenSeeD.git
|
| 5 |
+
cd OpenSeeD
|
| 6 |
+
mkdir serve
|
| 7 |
+
cp openseed_controlnet_worker.py openseed_controlnet_test_message.py serve/
|
| 8 |
+
mkdir ckpt
|
| 9 |
+
wget https://github.com/IDEA-Research/OpenSeeD/releases/download/ade20k_swinl/openseed_ade20k_swinl.pt
|
| 10 |
+
mv openseed_ade20k_swinl.pt ckpt/
|
| 11 |
+
```
|
| 12 |
+
## Run
|
| 13 |
+
```sh
|
| 14 |
+
#start worker
|
| 15 |
+
python serve/openseed_controlnet_worker.py
|
| 16 |
+
#test worker
|
| 17 |
+
python serve/openseed_controlnet_test_message.py
|
| 18 |
+
```
|
fin-mm/code/LLaVA-Plus/serve/ram_grounding_test_message.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
"box_threshold": args.box_threshold,
|
| 74 |
+
"text_threshold": args.text_threshold,
|
| 75 |
+
}
|
| 76 |
+
tic = time.time()
|
| 77 |
+
response = requests.post(
|
| 78 |
+
worker_addr + "/worker_generate",
|
| 79 |
+
headers=headers,
|
| 80 |
+
json=datas,
|
| 81 |
+
)
|
| 82 |
+
toc = time.time()
|
| 83 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 84 |
+
|
| 85 |
+
print("detection result:")
|
| 86 |
+
print(response.json())
|
| 87 |
+
# response is 'Response' with :
|
| 88 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# visualize
|
| 92 |
+
res = response.json()
|
| 93 |
+
boxes = torch.Tensor(res["boxes"])
|
| 94 |
+
logits = torch.Tensor(res["logits"])
|
| 95 |
+
phrases = res["phrases"]
|
| 96 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 97 |
+
annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 98 |
+
cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
parser = argparse.ArgumentParser()
|
| 102 |
+
# worker parameters
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument("--worker-address", type=str)
|
| 107 |
+
parser.add_argument("--model-name", type=str, default='ram+grounding_dino')
|
| 108 |
+
|
| 109 |
+
# model parameters
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--box_threshold", type=float, default=0.3,
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--text_threshold", type=float, default=0.25,
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--send_image", action="store_true",
|
| 121 |
+
)
|
| 122 |
+
args = parser.parse_args()
|
| 123 |
+
|
| 124 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/ram_grounding_worker.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
from groundingdino.util import box_ops
|
| 6 |
+
|
| 7 |
+
from segment_anything import build_sam
|
| 8 |
+
from segment_anything.predictor import SamPredictor
|
| 9 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import asyncio
|
| 13 |
+
import dataclasses
|
| 14 |
+
import logging
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from typing import List, Tuple, Union
|
| 20 |
+
import threading
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
from io import BytesIO
|
| 24 |
+
import base64
|
| 25 |
+
|
| 26 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 27 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 28 |
+
import numpy as np
|
| 29 |
+
import requests
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 33 |
+
|
| 34 |
+
from groundingdino.util.inference import load_model, predict
|
| 35 |
+
import groundingdino.datasets.transforms as T
|
| 36 |
+
import pycocotools.mask as mask_util
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from transformers import (
|
| 41 |
+
AutoTokenizer,
|
| 42 |
+
AutoModelForCausalLM,
|
| 43 |
+
LlamaTokenizer,
|
| 44 |
+
AutoModel,
|
| 45 |
+
)
|
| 46 |
+
except ImportError:
|
| 47 |
+
from transformers import (
|
| 48 |
+
AutoTokenizer,
|
| 49 |
+
AutoModelForCausalLM,
|
| 50 |
+
LLaMATokenizer,
|
| 51 |
+
AutoModel,
|
| 52 |
+
)
|
| 53 |
+
import torch
|
| 54 |
+
import torch.nn.functional as F
|
| 55 |
+
import uvicorn
|
| 56 |
+
|
| 57 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 58 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 59 |
+
|
| 60 |
+
GB = 1 << 30
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
now_file_name = os.__file__
|
| 64 |
+
logdir = "logs/workers/"
|
| 65 |
+
os.makedirs(logdir, exist_ok=True)
|
| 66 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 67 |
+
|
| 68 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 69 |
+
logger = build_logger(now_file_name, logfile)
|
| 70 |
+
global_counter = 0
|
| 71 |
+
|
| 72 |
+
model_semaphore = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def heart_beat_worker(controller):
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 78 |
+
controller.send_heart_beat()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelWorker:
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
controller_addr,
|
| 85 |
+
worker_addr,
|
| 86 |
+
worker_id,
|
| 87 |
+
no_register,
|
| 88 |
+
grounding_dino_server,
|
| 89 |
+
ram_server,
|
| 90 |
+
model_names,
|
| 91 |
+
device,
|
| 92 |
+
):
|
| 93 |
+
self.controller_addr = controller_addr
|
| 94 |
+
self.worker_addr = worker_addr
|
| 95 |
+
self.worker_id = worker_id
|
| 96 |
+
self.model_names = model_names
|
| 97 |
+
self.device = device
|
| 98 |
+
|
| 99 |
+
self.grounding_dino_server = grounding_dino_server
|
| 100 |
+
self.grounding_dino_server_addr = self.get_sub_worker_addr(grounding_dino_server)
|
| 101 |
+
print(f"grounding_dino_server_addr: {self.grounding_dino_server_addr}")
|
| 102 |
+
|
| 103 |
+
self.ram_server = ram_server
|
| 104 |
+
self.ram_server_addr = self.get_sub_worker_addr(ram_server)
|
| 105 |
+
print(f"ram_server_addr: {self.ram_server_addr}")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if not no_register:
|
| 109 |
+
self.register_to_controller()
|
| 110 |
+
self.heart_beat_thread = threading.Thread(
|
| 111 |
+
target=heart_beat_worker, args=(self,)
|
| 112 |
+
)
|
| 113 |
+
self.heart_beat_thread.start()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_sub_worker_addr(self, worker_name):
|
| 117 |
+
# get grounding dino addr
|
| 118 |
+
if worker_name.startswith("http"):
|
| 119 |
+
sub_server_addr = worker_name
|
| 120 |
+
else:
|
| 121 |
+
controller_addr = self.controller_addr
|
| 122 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 123 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 124 |
+
models = ret.json()["models"]
|
| 125 |
+
models.sort()
|
| 126 |
+
print(f"Models: {models}")
|
| 127 |
+
|
| 128 |
+
ret = requests.post(
|
| 129 |
+
controller_addr + "/get_worker_address", json={"model": worker_name}
|
| 130 |
+
)
|
| 131 |
+
sub_server_addr = ret.json()["address"]
|
| 132 |
+
# print(f"worker_name: {worker_name}")
|
| 133 |
+
return sub_server_addr
|
| 134 |
+
|
| 135 |
+
def register_to_controller(self):
|
| 136 |
+
logger.info("Register to controller")
|
| 137 |
+
|
| 138 |
+
url = self.controller_addr + "/register_worker"
|
| 139 |
+
data = {
|
| 140 |
+
"worker_name": self.worker_addr,
|
| 141 |
+
"check_heart_beat": True,
|
| 142 |
+
"worker_status": self.get_status(),
|
| 143 |
+
}
|
| 144 |
+
r = requests.post(url, json=data)
|
| 145 |
+
assert r.status_code == 200
|
| 146 |
+
|
| 147 |
+
def send_heart_beat(self):
|
| 148 |
+
logger.info(
|
| 149 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 150 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 151 |
+
f"global_counter: {global_counter}. "
|
| 152 |
+
f"worker_id: {worker_id}. "
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 156 |
+
|
| 157 |
+
while True:
|
| 158 |
+
try:
|
| 159 |
+
ret = requests.post(
|
| 160 |
+
url,
|
| 161 |
+
json={
|
| 162 |
+
"worker_name": self.worker_addr,
|
| 163 |
+
"queue_length": self.get_queue_length(),
|
| 164 |
+
},
|
| 165 |
+
timeout=5,
|
| 166 |
+
)
|
| 167 |
+
exist = ret.json()["exist"]
|
| 168 |
+
break
|
| 169 |
+
except requests.exceptions.RequestException as e:
|
| 170 |
+
logger.error(f"heart beat error: {e}")
|
| 171 |
+
time.sleep(5)
|
| 172 |
+
|
| 173 |
+
if not exist:
|
| 174 |
+
self.register_to_controller()
|
| 175 |
+
|
| 176 |
+
def get_queue_length(self):
|
| 177 |
+
if (
|
| 178 |
+
model_semaphore is None
|
| 179 |
+
or model_semaphore._value is None
|
| 180 |
+
or model_semaphore._waiters is None
|
| 181 |
+
):
|
| 182 |
+
return 0
|
| 183 |
+
else:
|
| 184 |
+
return (
|
| 185 |
+
args.limit_model_concurrency
|
| 186 |
+
- model_semaphore._value
|
| 187 |
+
+ len(model_semaphore._waiters)
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def get_status(self):
|
| 191 |
+
return {
|
| 192 |
+
"model_names": self.model_names,
|
| 193 |
+
"speed": 1,
|
| 194 |
+
"queue_length": self.get_queue_length(),
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if os.path.exists(image_path):
|
| 201 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 202 |
+
else:
|
| 203 |
+
# base64 coding
|
| 204 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 205 |
+
|
| 206 |
+
image = np.asarray(image_source)
|
| 207 |
+
image_transformed, _ = self.transform(image_source, None)
|
| 208 |
+
return image, image_transformed
|
| 209 |
+
|
| 210 |
+
def generate_stream_func(self, model, params, device):
|
| 211 |
+
# get inputs
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
headers = {"User-Agent": "G-SAM Client"}
|
| 216 |
+
|
| 217 |
+
# ram
|
| 218 |
+
pred_dict_ram = requests.post(
|
| 219 |
+
self.ram_server_addr + "/worker_generate",
|
| 220 |
+
headers=headers,
|
| 221 |
+
json=params,
|
| 222 |
+
).json()
|
| 223 |
+
|
| 224 |
+
params.update({
|
| 225 |
+
"caption": pred_dict_ram["tags"].replace(",", ".")
|
| 226 |
+
})
|
| 227 |
+
|
| 228 |
+
# gdino
|
| 229 |
+
pred_dict_gdino = requests.post(
|
| 230 |
+
self.grounding_dino_server_addr + "/worker_generate",
|
| 231 |
+
headers=headers,
|
| 232 |
+
json=params,
|
| 233 |
+
).json()
|
| 234 |
+
|
| 235 |
+
pred_dict_gdino.update({
|
| 236 |
+
"tags": pred_dict_ram["tags"],
|
| 237 |
+
"tags_chinese": pred_dict_ram["tags_chinese"],
|
| 238 |
+
})
|
| 239 |
+
|
| 240 |
+
return pred_dict_gdino
|
| 241 |
+
|
| 242 |
+
def generate_gate(self, params):
|
| 243 |
+
try:
|
| 244 |
+
|
| 245 |
+
ret = {"text": "", "error_code": 0}
|
| 246 |
+
ret = self.generate_stream_func(
|
| 247 |
+
None,
|
| 248 |
+
params,
|
| 249 |
+
self.device,
|
| 250 |
+
)
|
| 251 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 252 |
+
ret = {
|
| 253 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 254 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 255 |
+
}
|
| 256 |
+
except (ValueError, RuntimeError) as e:
|
| 257 |
+
ret = {
|
| 258 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 259 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 260 |
+
}
|
| 261 |
+
return ret
|
| 262 |
+
|
| 263 |
+
app = FastAPI()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def release_model_semaphore():
|
| 267 |
+
model_semaphore.release()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def acquire_model_semaphore():
|
| 271 |
+
global model_semaphore, global_counter
|
| 272 |
+
global_counter += 1
|
| 273 |
+
if model_semaphore is None:
|
| 274 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 275 |
+
return model_semaphore.acquire()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def create_background_tasks():
|
| 279 |
+
background_tasks = BackgroundTasks()
|
| 280 |
+
background_tasks.add_task(release_model_semaphore)
|
| 281 |
+
return background_tasks
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@app.post("/worker_generate")
|
| 286 |
+
async def api_generate(request: Request):
|
| 287 |
+
params = await request.json()
|
| 288 |
+
await acquire_model_semaphore()
|
| 289 |
+
output = worker.generate_gate(params)
|
| 290 |
+
release_model_semaphore()
|
| 291 |
+
return JSONResponse(output)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@app.post("/worker_get_status")
|
| 295 |
+
async def api_get_status(request: Request):
|
| 296 |
+
return worker.get_status()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@app.post("/model_details")
|
| 303 |
+
async def model_details(request: Request):
|
| 304 |
+
return {"context_length": worker.context_len}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
if __name__ == "__main__":
|
| 308 |
+
parser = argparse.ArgumentParser()
|
| 309 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 310 |
+
parser.add_argument("--port", type=int, default=22078)
|
| 311 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:22078")
|
| 312 |
+
parser.add_argument(
|
| 313 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
parser.add_argument(
|
| 317 |
+
"--grounding-dino-server", type=str, default="grounding_dino"
|
| 318 |
+
)
|
| 319 |
+
parser.add_argument(
|
| 320 |
+
"--ram-server", type=str, default="ram"
|
| 321 |
+
)
|
| 322 |
+
parser.add_argument(
|
| 323 |
+
"--model-names",
|
| 324 |
+
default="ram+grounding_dino",
|
| 325 |
+
type=lambda s: s.split(","),
|
| 326 |
+
help="Optional display comma separated names",
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 329 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 330 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 331 |
+
parser.add_argument("--no-register", action="store_true")
|
| 332 |
+
args = parser.parse_args()
|
| 333 |
+
logger.info(f"args: {args}")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
worker = ModelWorker(
|
| 337 |
+
args.controller_address,
|
| 338 |
+
args.worker_address,
|
| 339 |
+
worker_id,
|
| 340 |
+
args.no_register,
|
| 341 |
+
args.grounding_dino_server,
|
| 342 |
+
args.ram_server,
|
| 343 |
+
args.model_names,
|
| 344 |
+
args.device,
|
| 345 |
+
)
|
| 346 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/ram_test_message.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
def load_image(image_path):
|
| 19 |
+
img = Image.open(image_path).convert('RGB')
|
| 20 |
+
# import ipdb; ipdb.set_trace()
|
| 21 |
+
# resize if needed
|
| 22 |
+
w, h = img.size
|
| 23 |
+
if max(h, w) > 800:
|
| 24 |
+
if h > w:
|
| 25 |
+
new_h = 800
|
| 26 |
+
new_w = int(w * 800 / h)
|
| 27 |
+
else:
|
| 28 |
+
new_w = 800
|
| 29 |
+
new_h = int(h * 800 / w)
|
| 30 |
+
# import ipdb; ipdb.set_trace()
|
| 31 |
+
img = F.resize(img, (new_h, new_w))
|
| 32 |
+
return img
|
| 33 |
+
|
| 34 |
+
def encode(image: Image):
|
| 35 |
+
buffered = BytesIO()
|
| 36 |
+
image.save(buffered, format="JPEG")
|
| 37 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 38 |
+
return img_b64_str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
model_name = args.model_name
|
| 43 |
+
|
| 44 |
+
if args.worker_address:
|
| 45 |
+
worker_addr = args.worker_address
|
| 46 |
+
else:
|
| 47 |
+
controller_addr = args.controller_address
|
| 48 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 49 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 50 |
+
models = ret.json()["models"]
|
| 51 |
+
models.sort()
|
| 52 |
+
print(f"Models: {models}")
|
| 53 |
+
|
| 54 |
+
ret = requests.post(
|
| 55 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 56 |
+
)
|
| 57 |
+
worker_addr = ret.json()["address"]
|
| 58 |
+
print(f"worker_addr: {worker_addr}")
|
| 59 |
+
|
| 60 |
+
if worker_addr == "":
|
| 61 |
+
print(f"No available workers for {model_name}")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 65 |
+
if args.send_image:
|
| 66 |
+
img = load_image(args.image_path)
|
| 67 |
+
img_arg = encode(img)
|
| 68 |
+
else:
|
| 69 |
+
img_arg = args.image_path
|
| 70 |
+
datas = {
|
| 71 |
+
"model": model_name,
|
| 72 |
+
"image": img_arg,
|
| 73 |
+
}
|
| 74 |
+
tic = time.time()
|
| 75 |
+
response = requests.post(
|
| 76 |
+
worker_addr + "/worker_generate",
|
| 77 |
+
headers=headers,
|
| 78 |
+
json=datas,
|
| 79 |
+
)
|
| 80 |
+
toc = time.time()
|
| 81 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 82 |
+
|
| 83 |
+
print("detection result:")
|
| 84 |
+
print(response.json())
|
| 85 |
+
# response is 'Response' with :
|
| 86 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
parser = argparse.ArgumentParser()
|
| 93 |
+
# worker parameters
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--worker-address", type=str)
|
| 98 |
+
parser.add_argument("--model-name", type=str, default='ram')
|
| 99 |
+
|
| 100 |
+
# model parameters
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--send_image", action="store_true",
|
| 106 |
+
)
|
| 107 |
+
args = parser.parse_args()
|
| 108 |
+
|
| 109 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/ram_worker.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import asyncio
|
| 9 |
+
import dataclasses
|
| 10 |
+
import logging
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from typing import List, Tuple, Union
|
| 16 |
+
import threading
|
| 17 |
+
import uuid
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
import base64
|
| 21 |
+
|
| 22 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 23 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 24 |
+
import numpy as np
|
| 25 |
+
import requests
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
sys.path.append('Tag2Text')
|
| 29 |
+
from Tag2Text.models import tag2text
|
| 30 |
+
from Tag2Text import inference_ram
|
| 31 |
+
import torchvision.transforms as TS
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
from transformers import (
|
| 35 |
+
AutoTokenizer,
|
| 36 |
+
AutoModelForCausalLM,
|
| 37 |
+
LlamaTokenizer,
|
| 38 |
+
AutoModel,
|
| 39 |
+
)
|
| 40 |
+
except ImportError:
|
| 41 |
+
from transformers import (
|
| 42 |
+
AutoTokenizer,
|
| 43 |
+
AutoModelForCausalLM,
|
| 44 |
+
LLaMATokenizer,
|
| 45 |
+
AutoModel,
|
| 46 |
+
)
|
| 47 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 48 |
+
|
| 49 |
+
import torch
|
| 50 |
+
import torch.nn.functional as F
|
| 51 |
+
import uvicorn
|
| 52 |
+
|
| 53 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 54 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 55 |
+
|
| 56 |
+
GB = 1 << 30
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
now_file_name = os.__file__
|
| 60 |
+
logdir = "logs/workers/"
|
| 61 |
+
os.makedirs(logdir, exist_ok=True)
|
| 62 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 63 |
+
|
| 64 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 65 |
+
logger = build_logger(now_file_name, logfile)
|
| 66 |
+
global_counter = 0
|
| 67 |
+
|
| 68 |
+
model_semaphore = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def heart_beat_worker(controller):
|
| 72 |
+
while True:
|
| 73 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 74 |
+
controller.send_heart_beat()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ModelWorker:
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
controller_addr,
|
| 81 |
+
worker_addr,
|
| 82 |
+
worker_id,
|
| 83 |
+
no_register,
|
| 84 |
+
model_path,
|
| 85 |
+
model_names,
|
| 86 |
+
device,
|
| 87 |
+
):
|
| 88 |
+
self.controller_addr = controller_addr
|
| 89 |
+
self.worker_addr = worker_addr
|
| 90 |
+
self.worker_id = worker_id
|
| 91 |
+
if model_path.endswith("/"):
|
| 92 |
+
model_path = model_path[:-1]
|
| 93 |
+
self.model_names = model_names or [model_path.split("/")[-1]]
|
| 94 |
+
self.device = device
|
| 95 |
+
|
| 96 |
+
# load model
|
| 97 |
+
logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 98 |
+
self.ram_model = tag2text.ram(pretrained=model_path,
|
| 99 |
+
image_size=384,
|
| 100 |
+
vit='swin_l')
|
| 101 |
+
self.ram_model.to(device)
|
| 102 |
+
self.ram_model.eval()
|
| 103 |
+
|
| 104 |
+
if not no_register:
|
| 105 |
+
self.register_to_controller()
|
| 106 |
+
self.heart_beat_thread = threading.Thread(
|
| 107 |
+
target=heart_beat_worker, args=(self,)
|
| 108 |
+
)
|
| 109 |
+
self.heart_beat_thread.start()
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def register_to_controller(self):
|
| 114 |
+
logger.info("Register to controller")
|
| 115 |
+
|
| 116 |
+
url = self.controller_addr + "/register_worker"
|
| 117 |
+
data = {
|
| 118 |
+
"worker_name": self.worker_addr,
|
| 119 |
+
"check_heart_beat": True,
|
| 120 |
+
"worker_status": self.get_status(),
|
| 121 |
+
}
|
| 122 |
+
r = requests.post(url, json=data)
|
| 123 |
+
assert r.status_code == 200
|
| 124 |
+
|
| 125 |
+
def send_heart_beat(self):
|
| 126 |
+
logger.info(
|
| 127 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 128 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 129 |
+
f"global_counter: {global_counter}. "
|
| 130 |
+
f"worker_id: {worker_id}. "
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 134 |
+
|
| 135 |
+
while True:
|
| 136 |
+
try:
|
| 137 |
+
ret = requests.post(
|
| 138 |
+
url,
|
| 139 |
+
json={
|
| 140 |
+
"worker_name": self.worker_addr,
|
| 141 |
+
"queue_length": self.get_queue_length(),
|
| 142 |
+
},
|
| 143 |
+
timeout=5,
|
| 144 |
+
)
|
| 145 |
+
exist = ret.json()["exist"]
|
| 146 |
+
break
|
| 147 |
+
except requests.exceptions.RequestException as e:
|
| 148 |
+
logger.error(f"heart beat error: {e}")
|
| 149 |
+
time.sleep(5)
|
| 150 |
+
|
| 151 |
+
if not exist:
|
| 152 |
+
self.register_to_controller()
|
| 153 |
+
|
| 154 |
+
def get_queue_length(self):
|
| 155 |
+
if (
|
| 156 |
+
model_semaphore is None
|
| 157 |
+
or model_semaphore._value is None
|
| 158 |
+
or model_semaphore._waiters is None
|
| 159 |
+
):
|
| 160 |
+
return 0
|
| 161 |
+
else:
|
| 162 |
+
return (
|
| 163 |
+
args.limit_model_concurrency
|
| 164 |
+
- model_semaphore._value
|
| 165 |
+
+ len(model_semaphore._waiters)
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def get_status(self):
|
| 169 |
+
return {
|
| 170 |
+
"model_names": self.model_names,
|
| 171 |
+
"speed": 1,
|
| 172 |
+
"queue_length": self.get_queue_length(),
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if os.path.exists(image_path):
|
| 179 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 180 |
+
else:
|
| 181 |
+
# base64 coding
|
| 182 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 183 |
+
|
| 184 |
+
normalize = TS.Normalize(mean=[0.485, 0.456, 0.406],
|
| 185 |
+
std=[0.229, 0.224, 0.225])
|
| 186 |
+
transform = TS.Compose([
|
| 187 |
+
TS.Resize((384, 384)),
|
| 188 |
+
TS.ToTensor(), normalize
|
| 189 |
+
])
|
| 190 |
+
image_source = transform(image_source)
|
| 191 |
+
return image_source
|
| 192 |
+
|
| 193 |
+
def generate_stream_func(self, model, params, device):
|
| 194 |
+
# get inputs
|
| 195 |
+
image_path = params["image"]
|
| 196 |
+
|
| 197 |
+
# load image and run models
|
| 198 |
+
image = self.load_image(image_path).unsqueeze(0).to(device)
|
| 199 |
+
|
| 200 |
+
# tagging:
|
| 201 |
+
res = inference_ram.inference(image , self.ram_model)
|
| 202 |
+
|
| 203 |
+
tags=res[0].replace(' |', ',')
|
| 204 |
+
tags_chinese=res[1].replace(' |', ',')
|
| 205 |
+
|
| 206 |
+
_, __, h, w = image.shape
|
| 207 |
+
pred_dict = {
|
| 208 |
+
"tags": tags,
|
| 209 |
+
"tags_chinese": tags_chinese,
|
| 210 |
+
"size": [h, w], # H,W
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
return pred_dict
|
| 214 |
+
|
| 215 |
+
def generate_gate(self, params):
|
| 216 |
+
try:
|
| 217 |
+
|
| 218 |
+
ret = {"text": "", "error_code": 0}
|
| 219 |
+
ret = self.generate_stream_func(
|
| 220 |
+
self.ram_model,
|
| 221 |
+
params,
|
| 222 |
+
self.device,
|
| 223 |
+
)
|
| 224 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 225 |
+
ret = {
|
| 226 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 227 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 228 |
+
}
|
| 229 |
+
except (ValueError, RuntimeError) as e:
|
| 230 |
+
ret = {
|
| 231 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 232 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 233 |
+
}
|
| 234 |
+
return ret
|
| 235 |
+
|
| 236 |
+
@torch.inference_mode()
|
| 237 |
+
def get_embeddings(self, params):
|
| 238 |
+
try:
|
| 239 |
+
tokenizer = self.tokenizer
|
| 240 |
+
is_llama = "llama" in str(
|
| 241 |
+
type(self.model)
|
| 242 |
+
) # vicuna support batch inference
|
| 243 |
+
is_chatglm = "chatglm" in str(type(self.model))
|
| 244 |
+
is_t5 = "t5" in str(type(self.model))
|
| 245 |
+
if is_llama:
|
| 246 |
+
encoding = tokenizer.batch_encode_plus(
|
| 247 |
+
params["input"], padding=True, return_tensors="pt"
|
| 248 |
+
)
|
| 249 |
+
input_ids = encoding["input_ids"].to(self.device)
|
| 250 |
+
attention_mask = encoding["attention_mask"].to(self.device)
|
| 251 |
+
model_output = self.model(
|
| 252 |
+
input_ids, attention_mask, output_hidden_states=True
|
| 253 |
+
)
|
| 254 |
+
data = model_output.hidden_states[-1]
|
| 255 |
+
mask = attention_mask.unsqueeze(-1).expand(data.size()).float()
|
| 256 |
+
masked_embeddings = data * mask
|
| 257 |
+
sum_embeddings = torch.sum(masked_embeddings, dim=1)
|
| 258 |
+
seq_length = torch.sum(mask, dim=1)
|
| 259 |
+
embedding = sum_embeddings / seq_length
|
| 260 |
+
normalized_embeddings = F.normalize(embedding, p=2, dim=1)
|
| 261 |
+
ret = {
|
| 262 |
+
"embedding": normalized_embeddings.tolist(),
|
| 263 |
+
"token_num": torch.sum(attention_mask).item(),
|
| 264 |
+
}
|
| 265 |
+
else:
|
| 266 |
+
embedding = []
|
| 267 |
+
token_num = 0
|
| 268 |
+
for text in params["input"]:
|
| 269 |
+
input_ids = tokenizer.encode(text, return_tensors="pt").to(
|
| 270 |
+
self.device
|
| 271 |
+
)
|
| 272 |
+
if is_t5:
|
| 273 |
+
model_output = self.model(
|
| 274 |
+
input_ids, decoder_input_ids=input_ids
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
model_output = self.model(input_ids, output_hidden_states=True)
|
| 278 |
+
if is_chatglm:
|
| 279 |
+
data = (model_output.hidden_states[-1].transpose(0, 1))[0]
|
| 280 |
+
elif is_t5:
|
| 281 |
+
data = model_output.encoder_last_hidden_state[0]
|
| 282 |
+
else:
|
| 283 |
+
data = model_output.hidden_states[-1][0]
|
| 284 |
+
data = F.normalize(torch.mean(data, dim=0), p=2, dim=0)
|
| 285 |
+
embedding.append(data.tolist())
|
| 286 |
+
token_num += len(input_ids[0])
|
| 287 |
+
ret = {
|
| 288 |
+
"embedding": embedding,
|
| 289 |
+
"token_num": token_num,
|
| 290 |
+
}
|
| 291 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 292 |
+
ret = {
|
| 293 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 294 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 295 |
+
}
|
| 296 |
+
except (ValueError, RuntimeError) as e:
|
| 297 |
+
ret = {
|
| 298 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 299 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 300 |
+
}
|
| 301 |
+
return ret
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
app = FastAPI()
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def release_model_semaphore():
|
| 308 |
+
model_semaphore.release()
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def acquire_model_semaphore():
|
| 312 |
+
global model_semaphore, global_counter
|
| 313 |
+
global_counter += 1
|
| 314 |
+
if model_semaphore is None:
|
| 315 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 316 |
+
return model_semaphore.acquire()
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def create_background_tasks():
|
| 320 |
+
background_tasks = BackgroundTasks()
|
| 321 |
+
background_tasks.add_task(release_model_semaphore)
|
| 322 |
+
return background_tasks
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@app.post("/worker_generate")
|
| 327 |
+
async def api_generate(request: Request):
|
| 328 |
+
params = await request.json()
|
| 329 |
+
await acquire_model_semaphore()
|
| 330 |
+
output = worker.generate_gate(params)
|
| 331 |
+
release_model_semaphore()
|
| 332 |
+
return JSONResponse(output)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
@app.post("/worker_get_status")
|
| 336 |
+
async def api_get_status(request: Request):
|
| 337 |
+
return worker.get_status()
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
@app.post("/model_details")
|
| 344 |
+
async def model_details(request: Request):
|
| 345 |
+
return {"context_length": worker.context_len}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
parser = argparse.ArgumentParser()
|
| 350 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 351 |
+
parser.add_argument("--port", type=int, default=21009)
|
| 352 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21009")
|
| 353 |
+
parser.add_argument(
|
| 354 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"--model-path", type=str, default="ram_swin_large_14m.pth"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
parser.add_argument(
|
| 362 |
+
"--model-names",
|
| 363 |
+
default="ram",
|
| 364 |
+
type=lambda s: s.split(","),
|
| 365 |
+
help="Optional display comma separated names",
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 368 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 369 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 370 |
+
parser.add_argument("--no-register", action="store_true")
|
| 371 |
+
args = parser.parse_args()
|
| 372 |
+
logger.info(f"args: {args}")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
worker = ModelWorker(
|
| 376 |
+
args.controller_address,
|
| 377 |
+
args.worker_address,
|
| 378 |
+
worker_id,
|
| 379 |
+
args.no_register,
|
| 380 |
+
args.model_path,
|
| 381 |
+
args.model_names,
|
| 382 |
+
args.device,
|
| 383 |
+
)
|
| 384 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/sam_test_message.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
from groundingdino.util.inference import annotate, annotate_xyxy
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import base64
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torchvision.transforms.functional as F
|
| 17 |
+
|
| 18 |
+
import pycocotools.mask as mask_util
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_image(image_path):
|
| 22 |
+
img = Image.open(image_path).convert('RGB')
|
| 23 |
+
# import ipdb; ipdb.set_trace()
|
| 24 |
+
# resize if needed
|
| 25 |
+
w, h = img.size
|
| 26 |
+
if max(h, w) > 800:
|
| 27 |
+
if h > w:
|
| 28 |
+
new_h = 800
|
| 29 |
+
new_w = int(w * 800 / h)
|
| 30 |
+
else:
|
| 31 |
+
new_w = 800
|
| 32 |
+
new_h = int(h * 800 / w)
|
| 33 |
+
# import ipdb; ipdb.set_trace()
|
| 34 |
+
img = F.resize(img, (new_h, new_w))
|
| 35 |
+
return img
|
| 36 |
+
|
| 37 |
+
def encode(image: Image):
|
| 38 |
+
buffered = BytesIO()
|
| 39 |
+
image.save(buffered, format="JPEG")
|
| 40 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 41 |
+
return img_b64_str
|
| 42 |
+
|
| 43 |
+
def show_mask(mask, image, random_color=True):
|
| 44 |
+
if random_color:
|
| 45 |
+
color = np.concatenate([np.random.random(3), np.array([0.8])], axis=0)
|
| 46 |
+
else:
|
| 47 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 48 |
+
h, w = mask.shape[-2:]
|
| 49 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 50 |
+
|
| 51 |
+
annotated_frame_pil = Image.fromarray(image).convert("RGBA")
|
| 52 |
+
mask_image_pil = Image.fromarray((mask_image.cpu().numpy() * 255).astype(np.uint8)).convert("RGBA")
|
| 53 |
+
|
| 54 |
+
return np.array(Image.alpha_composite(annotated_frame_pil, mask_image_pil))
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
model_name = args.model_name
|
| 58 |
+
|
| 59 |
+
if args.worker_address:
|
| 60 |
+
worker_addr = args.worker_address
|
| 61 |
+
else:
|
| 62 |
+
controller_addr = args.controller_address
|
| 63 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 64 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 65 |
+
models = ret.json()["models"]
|
| 66 |
+
models.sort()
|
| 67 |
+
print(f"Models: {models}")
|
| 68 |
+
|
| 69 |
+
ret = requests.post(
|
| 70 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 71 |
+
)
|
| 72 |
+
worker_addr = ret.json()["address"]
|
| 73 |
+
print(f"worker_addr: {worker_addr}")
|
| 74 |
+
|
| 75 |
+
if worker_addr == "":
|
| 76 |
+
print(f"No available workers for {model_name}")
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 80 |
+
if args.send_image:
|
| 81 |
+
img = load_image(args.image_path)
|
| 82 |
+
img_arg = encode(img)
|
| 83 |
+
else:
|
| 84 |
+
img_arg = args.image_path
|
| 85 |
+
img = None
|
| 86 |
+
datas = {
|
| 87 |
+
"model": model_name,
|
| 88 |
+
"image": img_arg,
|
| 89 |
+
"boxes": args.boxes,
|
| 90 |
+
}
|
| 91 |
+
tic = time.time()
|
| 92 |
+
response = requests.post(
|
| 93 |
+
worker_addr + "/worker_generate",
|
| 94 |
+
headers=headers,
|
| 95 |
+
json=datas,
|
| 96 |
+
)
|
| 97 |
+
toc = time.time()
|
| 98 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 99 |
+
|
| 100 |
+
print("detection result:")
|
| 101 |
+
print(response.json())
|
| 102 |
+
# response is 'Response' with :
|
| 103 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 104 |
+
|
| 105 |
+
# visualize
|
| 106 |
+
res = response.json()
|
| 107 |
+
res['boxes'] = args.boxes
|
| 108 |
+
boxes = torch.Tensor(res["boxes"])
|
| 109 |
+
logits = torch.ones(boxes.shape[0])
|
| 110 |
+
phrases = ['' for _ in range(boxes.shape[0])]
|
| 111 |
+
if img is not None:
|
| 112 |
+
image_source = np.array(img.convert("RGB"))
|
| 113 |
+
else:
|
| 114 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 115 |
+
annotated_frame = annotate_xyxy(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 116 |
+
# cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 117 |
+
|
| 118 |
+
# show mask
|
| 119 |
+
masks_rle = res["masks_rle"]
|
| 120 |
+
for mask_rle in masks_rle:
|
| 121 |
+
mask = mask_util.decode(mask_rle)
|
| 122 |
+
mask = torch.Tensor(mask)
|
| 123 |
+
annotated_frame = show_mask(mask, annotated_frame)
|
| 124 |
+
cv2.imwrite("annotated_image_mask.jpg", annotated_frame)
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
parser = argparse.ArgumentParser()
|
| 128 |
+
# worker parameters
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 131 |
+
)
|
| 132 |
+
parser.add_argument("--worker-address", type=str)
|
| 133 |
+
parser.add_argument("--model-name", type=str, default='sam')
|
| 134 |
+
|
| 135 |
+
# model parameters
|
| 136 |
+
parser.add_argument(
|
| 137 |
+
"--caption", type=str, default="dogs ."
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--boxes",
|
| 141 |
+
default="[[0.1, 0.2, 0.8, 0.5], [0.3, 0.5, 0.9, 0.9]]",
|
| 142 |
+
type=lambda s: eval(s),
|
| 143 |
+
help="Optional display comma separated names",
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument(
|
| 146 |
+
"--image_path", type=str, default="assets/demo2.jpg"
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--send_image", action="store_true",
|
| 150 |
+
)
|
| 151 |
+
args = parser.parse_args()
|
| 152 |
+
|
| 153 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/sam_test_message_points.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import random
|
| 5 |
+
import time
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
import cv2
|
| 8 |
+
from groundingdino.util.inference import annotate, annotate_xyxy
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import base64
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torchvision.transforms.functional as F
|
| 18 |
+
|
| 19 |
+
import pycocotools.mask as mask_util
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_image(image_path):
|
| 23 |
+
img = Image.open(image_path).convert('RGB')
|
| 24 |
+
# import ipdb; ipdb.set_trace()
|
| 25 |
+
# resize if needed
|
| 26 |
+
w, h = img.size
|
| 27 |
+
if max(h, w) > 800:
|
| 28 |
+
if h > w:
|
| 29 |
+
new_h = 800
|
| 30 |
+
new_w = int(w * 800 / h)
|
| 31 |
+
else:
|
| 32 |
+
new_w = 800
|
| 33 |
+
new_h = int(h * 800 / w)
|
| 34 |
+
# import ipdb; ipdb.set_trace()
|
| 35 |
+
img = F.resize(img, (new_h, new_w))
|
| 36 |
+
return img
|
| 37 |
+
|
| 38 |
+
def encode(image: Image):
|
| 39 |
+
buffered = BytesIO()
|
| 40 |
+
image.save(buffered, format="JPEG")
|
| 41 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 42 |
+
return img_b64_str
|
| 43 |
+
|
| 44 |
+
def show_mask(mask, image, random_color=True):
|
| 45 |
+
if random_color:
|
| 46 |
+
color = np.concatenate([np.random.random(3), np.array([0.8])], axis=0)
|
| 47 |
+
else:
|
| 48 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 49 |
+
h, w = mask.shape[-2:]
|
| 50 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 51 |
+
|
| 52 |
+
annotated_frame_pil = Image.fromarray(image).convert("RGBA")
|
| 53 |
+
mask_image_pil = Image.fromarray((mask_image.cpu().numpy() * 255).astype(np.uint8)).convert("RGBA")
|
| 54 |
+
|
| 55 |
+
return np.array(Image.alpha_composite(annotated_frame_pil, mask_image_pil))
|
| 56 |
+
|
| 57 |
+
def main():
|
| 58 |
+
model_name = args.model_name
|
| 59 |
+
|
| 60 |
+
if args.worker_address:
|
| 61 |
+
worker_addr = args.worker_address
|
| 62 |
+
else:
|
| 63 |
+
controller_addr = args.controller_address
|
| 64 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 65 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 66 |
+
models = ret.json()["models"]
|
| 67 |
+
models.sort()
|
| 68 |
+
print(f"Models: {models}")
|
| 69 |
+
|
| 70 |
+
ret = requests.post(
|
| 71 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 72 |
+
)
|
| 73 |
+
worker_addr = ret.json()["address"]
|
| 74 |
+
print(f"worker_addr: {worker_addr}")
|
| 75 |
+
|
| 76 |
+
if worker_addr == "":
|
| 77 |
+
print(f"No available workers for {model_name}")
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 81 |
+
if args.send_image:
|
| 82 |
+
img = load_image(args.image_path)
|
| 83 |
+
img_arg = encode(img)
|
| 84 |
+
else:
|
| 85 |
+
img_arg = args.image_path
|
| 86 |
+
img = None
|
| 87 |
+
|
| 88 |
+
# random points
|
| 89 |
+
points = np.random.rand(1, 3, 2).tolist()
|
| 90 |
+
point_labels = (np.random.rand(1, 3) > 0.5).astype(np.int32).tolist()
|
| 91 |
+
if sum(point_labels[0]) == 0:
|
| 92 |
+
point_labels[0][random.randint(0, 2)] = 1
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
datas = {
|
| 97 |
+
"model": model_name,
|
| 98 |
+
"image": img_arg,
|
| 99 |
+
"points": points,
|
| 100 |
+
"point_labels": point_labels,
|
| 101 |
+
}
|
| 102 |
+
tic = time.time()
|
| 103 |
+
response = requests.post(
|
| 104 |
+
worker_addr + "/worker_generate",
|
| 105 |
+
headers=headers,
|
| 106 |
+
json=datas,
|
| 107 |
+
)
|
| 108 |
+
toc = time.time()
|
| 109 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 110 |
+
|
| 111 |
+
print("detection result:")
|
| 112 |
+
print(response.json())
|
| 113 |
+
# response is 'Response' with :
|
| 114 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 115 |
+
|
| 116 |
+
# visualize
|
| 117 |
+
res = response.json()
|
| 118 |
+
# res['boxes'] = args.boxes
|
| 119 |
+
# boxes = torch.Tensor(res["boxes"])
|
| 120 |
+
# logits = torch.ones(boxes.shape[0])
|
| 121 |
+
# phrases = ['' for _ in range(boxes.shape[0])]
|
| 122 |
+
if img is not None:
|
| 123 |
+
image_source = np.array(img.convert("RGB"))
|
| 124 |
+
else:
|
| 125 |
+
image_source = np.array(Image.open(args.image_path).convert("RGB"))
|
| 126 |
+
# annotated_frame = annotate_xyxy(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
|
| 127 |
+
# cv2.imwrite("annotated_image.jpg", annotated_frame)
|
| 128 |
+
|
| 129 |
+
# show mask
|
| 130 |
+
masks_rle = res["masks_rle"]
|
| 131 |
+
for mask_rle in masks_rle:
|
| 132 |
+
mask = mask_util.decode(mask_rle)
|
| 133 |
+
mask = torch.Tensor(mask)
|
| 134 |
+
annotated_frame = show_mask(mask, image_source)
|
| 135 |
+
annotated_frame = cv2.cvtColor(annotated_frame, cv2.COLOR_RGB2BGR)
|
| 136 |
+
|
| 137 |
+
# show points
|
| 138 |
+
points = np.array(points)
|
| 139 |
+
point_labels = np.array(point_labels)
|
| 140 |
+
h, w = annotated_frame.shape[:2]
|
| 141 |
+
for i in range(points.shape[1]):
|
| 142 |
+
color = (0, 255, 0) if point_labels[0, i] == 1 else (0, 0, 255)
|
| 143 |
+
annotated_frame = cv2.circle(annotated_frame, (int(points[0, i, 0] * w), int(points[0, i, 1] * h)), 5, color, -1)
|
| 144 |
+
cv2.imwrite("annotated_image_mask.jpg", annotated_frame)
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
parser = argparse.ArgumentParser()
|
| 148 |
+
# worker parameters
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument("--worker-address", type=str)
|
| 153 |
+
parser.add_argument("--model-name", type=str, default='sam')
|
| 154 |
+
|
| 155 |
+
# model parameters
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--caption", type=str, default="dogs ."
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument(
|
| 160 |
+
"--image_path", type=str, default="/home/liushilong/code/GroundingFolder/Grounded-Segment-Anything/assets/demo2.jpg"
|
| 161 |
+
)
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--send_image", action="store_true",
|
| 164 |
+
)
|
| 165 |
+
args = parser.parse_args()
|
| 166 |
+
|
| 167 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/sam_worker.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
from groundingdino.util import box_ops
|
| 6 |
+
|
| 7 |
+
from segment_anything import build_sam
|
| 8 |
+
from segment_anything.predictor import SamPredictor
|
| 9 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import asyncio
|
| 13 |
+
import dataclasses
|
| 14 |
+
import logging
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
from typing import List, Tuple, Union
|
| 20 |
+
import threading
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
from io import BytesIO
|
| 24 |
+
import base64
|
| 25 |
+
|
| 26 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 27 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 28 |
+
import numpy as np
|
| 29 |
+
import requests
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from demo.inference_on_a_image import get_grounding_output
|
| 33 |
+
|
| 34 |
+
from groundingdino.util.inference import load_model, predict
|
| 35 |
+
import groundingdino.datasets.transforms as T
|
| 36 |
+
import pycocotools.mask as mask_util
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from transformers import (
|
| 41 |
+
AutoTokenizer,
|
| 42 |
+
AutoModelForCausalLM,
|
| 43 |
+
LlamaTokenizer,
|
| 44 |
+
AutoModel,
|
| 45 |
+
)
|
| 46 |
+
except ImportError:
|
| 47 |
+
from transformers import (
|
| 48 |
+
AutoTokenizer,
|
| 49 |
+
AutoModelForCausalLM,
|
| 50 |
+
LLaMATokenizer,
|
| 51 |
+
AutoModel,
|
| 52 |
+
)
|
| 53 |
+
import torch
|
| 54 |
+
import torch.nn.functional as F
|
| 55 |
+
import uvicorn
|
| 56 |
+
|
| 57 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 58 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 59 |
+
|
| 60 |
+
GB = 1 << 30
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
now_file_name = os.__file__
|
| 64 |
+
logdir = "logs/workers/"
|
| 65 |
+
os.makedirs(logdir, exist_ok=True)
|
| 66 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 67 |
+
|
| 68 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 69 |
+
logger = build_logger(now_file_name, logfile)
|
| 70 |
+
global_counter = 0
|
| 71 |
+
|
| 72 |
+
model_semaphore = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def heart_beat_worker(controller):
|
| 76 |
+
while True:
|
| 77 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 78 |
+
controller.send_heart_beat()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelWorker:
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
controller_addr,
|
| 85 |
+
worker_addr,
|
| 86 |
+
worker_id,
|
| 87 |
+
no_register,
|
| 88 |
+
model_names,
|
| 89 |
+
sam_path,
|
| 90 |
+
device,
|
| 91 |
+
):
|
| 92 |
+
self.controller_addr = controller_addr
|
| 93 |
+
self.worker_addr = worker_addr
|
| 94 |
+
self.worker_id = worker_id
|
| 95 |
+
self.model_names = model_names
|
| 96 |
+
self.device = device
|
| 97 |
+
|
| 98 |
+
if not no_register:
|
| 99 |
+
self.register_to_controller()
|
| 100 |
+
self.heart_beat_thread = threading.Thread(
|
| 101 |
+
target=heart_beat_worker, args=(self,)
|
| 102 |
+
)
|
| 103 |
+
self.heart_beat_thread.start()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# load sam model
|
| 107 |
+
self.sam = build_sam(checkpoint=sam_path)
|
| 108 |
+
self.sam.to(device=device)
|
| 109 |
+
self.sam_predictor = SamPredictor(self.sam)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def register_to_controller(self):
|
| 114 |
+
logger.info("Register to controller")
|
| 115 |
+
|
| 116 |
+
url = self.controller_addr + "/register_worker"
|
| 117 |
+
data = {
|
| 118 |
+
"worker_name": self.worker_addr,
|
| 119 |
+
"check_heart_beat": True,
|
| 120 |
+
"worker_status": self.get_status(),
|
| 121 |
+
}
|
| 122 |
+
r = requests.post(url, json=data)
|
| 123 |
+
assert r.status_code == 200
|
| 124 |
+
|
| 125 |
+
def send_heart_beat(self):
|
| 126 |
+
logger.info(
|
| 127 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 128 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 129 |
+
f"global_counter: {global_counter}. "
|
| 130 |
+
f"worker_id: {worker_id}. "
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 134 |
+
|
| 135 |
+
while True:
|
| 136 |
+
try:
|
| 137 |
+
ret = requests.post(
|
| 138 |
+
url,
|
| 139 |
+
json={
|
| 140 |
+
"worker_name": self.worker_addr,
|
| 141 |
+
"queue_length": self.get_queue_length(),
|
| 142 |
+
},
|
| 143 |
+
timeout=5,
|
| 144 |
+
)
|
| 145 |
+
exist = ret.json()["exist"]
|
| 146 |
+
break
|
| 147 |
+
except requests.exceptions.RequestException as e:
|
| 148 |
+
logger.error(f"heart beat error: {e}")
|
| 149 |
+
time.sleep(5)
|
| 150 |
+
|
| 151 |
+
if not exist:
|
| 152 |
+
self.register_to_controller()
|
| 153 |
+
|
| 154 |
+
def get_queue_length(self):
|
| 155 |
+
if (
|
| 156 |
+
model_semaphore is None
|
| 157 |
+
or model_semaphore._value is None
|
| 158 |
+
or model_semaphore._waiters is None
|
| 159 |
+
):
|
| 160 |
+
return 0
|
| 161 |
+
else:
|
| 162 |
+
return (
|
| 163 |
+
args.limit_model_concurrency
|
| 164 |
+
- model_semaphore._value
|
| 165 |
+
+ len(model_semaphore._waiters)
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def get_status(self):
|
| 169 |
+
return {
|
| 170 |
+
"model_names": self.model_names,
|
| 171 |
+
"speed": 1,
|
| 172 |
+
"queue_length": self.get_queue_length(),
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
def load_image(self, image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if os.path.exists(image_path):
|
| 179 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 180 |
+
else:
|
| 181 |
+
# base64 coding
|
| 182 |
+
image_source = Image.open(BytesIO(base64.b64decode(image_path))).convert("RGB")
|
| 183 |
+
|
| 184 |
+
image = np.asarray(image_source)
|
| 185 |
+
# image_transformed, _ = self.transform(image_source, None)
|
| 186 |
+
return image, None
|
| 187 |
+
|
| 188 |
+
def generate_stream_func(self, model, params, device):
|
| 189 |
+
# get inputs
|
| 190 |
+
image_path = params["image"]
|
| 191 |
+
|
| 192 |
+
boxes = params.get("boxes", None) # b, 4
|
| 193 |
+
points = params.get("points", None) # b, n, 2
|
| 194 |
+
point_labels = params.get("point_labels", None) # b, n. (1 indicates a foreground point and 0 indicates a background point.)
|
| 195 |
+
|
| 196 |
+
assert not (boxes is None and points is None), "boxes and points cannot be both None"
|
| 197 |
+
assert not (boxes is not None and points is not None), "boxes and points cannot be both not None"
|
| 198 |
+
|
| 199 |
+
image_np, _ = self.load_image(image_path)
|
| 200 |
+
h, w, _ = image_np.shape
|
| 201 |
+
|
| 202 |
+
# add sam output
|
| 203 |
+
if boxes is not None:
|
| 204 |
+
if len(boxes) > 0:
|
| 205 |
+
boxes_tensor = torch.Tensor(boxes).to(device)
|
| 206 |
+
boxes_xyxy = boxes_tensor * torch.Tensor([w, h, w, h]).to(device)
|
| 207 |
+
self.sam_predictor.set_image(image_np)
|
| 208 |
+
transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_xyxy, image_np.shape[:2]).to(device)
|
| 209 |
+
# import ipdb; ipdb.set_trace()
|
| 210 |
+
masks, _, _ = self.sam_predictor.predict_torch(
|
| 211 |
+
point_coords = None,
|
| 212 |
+
point_labels = None,
|
| 213 |
+
boxes = transformed_boxes,
|
| 214 |
+
multimask_output = False,
|
| 215 |
+
)
|
| 216 |
+
masks = masks[:, 0] # B, H, W
|
| 217 |
+
|
| 218 |
+
# encoder masks to strs
|
| 219 |
+
maskrls_list = []
|
| 220 |
+
for mask in masks:
|
| 221 |
+
mask_rle = mask_util.encode(np.array(mask[:, :, None].cpu(), order="F"))[0]
|
| 222 |
+
mask_rle["counts"] = mask_rle["counts"].decode("utf-8")
|
| 223 |
+
maskrls_list.append(mask_rle)
|
| 224 |
+
else:
|
| 225 |
+
maskrls_list = []
|
| 226 |
+
elif points is not None:
|
| 227 |
+
assert point_labels is not None, "point_labels cannot be None when points is not None"
|
| 228 |
+
if len(points) > 0:
|
| 229 |
+
points_tensor = torch.Tensor(points).to(device) * torch.Tensor([w, h]).to(device)
|
| 230 |
+
self.sam_predictor.set_image(image_np)
|
| 231 |
+
transformed_points = self.sam_predictor.transform.apply_coords_torch(points_tensor, image_np.shape[:2]).to(device)
|
| 232 |
+
|
| 233 |
+
point_labels_tensor = torch.Tensor(point_labels).to(device)
|
| 234 |
+
# import ipdb; ipdb.set_trace()
|
| 235 |
+
masks, _, _ = self.sam_predictor.predict_torch(
|
| 236 |
+
point_coords = transformed_points, # b, n, 2
|
| 237 |
+
point_labels = point_labels_tensor, # b, n. 1 indicates a foreground point and 0 indicates a background point.
|
| 238 |
+
boxes = None,
|
| 239 |
+
multimask_output = False,
|
| 240 |
+
)
|
| 241 |
+
masks = masks[:, 0] # B, H, W
|
| 242 |
+
|
| 243 |
+
# encoder masks to strs
|
| 244 |
+
maskrls_list = []
|
| 245 |
+
for mask in masks:
|
| 246 |
+
mask_rle = mask_util.encode(np.array(mask[:, :, None].cpu(), order="F"))[0]
|
| 247 |
+
mask_rle["counts"] = mask_rle["counts"].decode("utf-8")
|
| 248 |
+
maskrls_list.append(mask_rle)
|
| 249 |
+
else:
|
| 250 |
+
maskrls_list = []
|
| 251 |
+
|
| 252 |
+
pred_dict = {}
|
| 253 |
+
pred_dict['masks_rle'] = maskrls_list
|
| 254 |
+
pred_dict['boxes'] = boxes
|
| 255 |
+
return pred_dict
|
| 256 |
+
|
| 257 |
+
def generate_gate(self, params):
|
| 258 |
+
try:
|
| 259 |
+
|
| 260 |
+
ret = {"text": "", "error_code": 0}
|
| 261 |
+
ret = self.generate_stream_func(
|
| 262 |
+
None,
|
| 263 |
+
params,
|
| 264 |
+
self.device,
|
| 265 |
+
)
|
| 266 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 267 |
+
ret = {
|
| 268 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 269 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 270 |
+
}
|
| 271 |
+
except (ValueError, RuntimeError) as e:
|
| 272 |
+
ret = {
|
| 273 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 274 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 275 |
+
}
|
| 276 |
+
return ret
|
| 277 |
+
|
| 278 |
+
@torch.inference_mode()
|
| 279 |
+
def get_embeddings(self, params):
|
| 280 |
+
try:
|
| 281 |
+
tokenizer = self.tokenizer
|
| 282 |
+
is_llama = "llama" in str(
|
| 283 |
+
type(self.model)
|
| 284 |
+
) # vicuna support batch inference
|
| 285 |
+
is_chatglm = "chatglm" in str(type(self.model))
|
| 286 |
+
is_t5 = "t5" in str(type(self.model))
|
| 287 |
+
if is_llama:
|
| 288 |
+
encoding = tokenizer.batch_encode_plus(
|
| 289 |
+
params["input"], padding=True, return_tensors="pt"
|
| 290 |
+
)
|
| 291 |
+
input_ids = encoding["input_ids"].to(self.device)
|
| 292 |
+
attention_mask = encoding["attention_mask"].to(self.device)
|
| 293 |
+
model_output = self.model(
|
| 294 |
+
input_ids, attention_mask, output_hidden_states=True
|
| 295 |
+
)
|
| 296 |
+
data = model_output.hidden_states[-1]
|
| 297 |
+
mask = attention_mask.unsqueeze(-1).expand(data.size()).float()
|
| 298 |
+
masked_embeddings = data * mask
|
| 299 |
+
sum_embeddings = torch.sum(masked_embeddings, dim=1)
|
| 300 |
+
seq_length = torch.sum(mask, dim=1)
|
| 301 |
+
embedding = sum_embeddings / seq_length
|
| 302 |
+
normalized_embeddings = F.normalize(embedding, p=2, dim=1)
|
| 303 |
+
ret = {
|
| 304 |
+
"embedding": normalized_embeddings.tolist(),
|
| 305 |
+
"token_num": torch.sum(attention_mask).item(),
|
| 306 |
+
}
|
| 307 |
+
else:
|
| 308 |
+
embedding = []
|
| 309 |
+
token_num = 0
|
| 310 |
+
for text in params["input"]:
|
| 311 |
+
input_ids = tokenizer.encode(text, return_tensors="pt").to(
|
| 312 |
+
self.device
|
| 313 |
+
)
|
| 314 |
+
if is_t5:
|
| 315 |
+
model_output = self.model(
|
| 316 |
+
input_ids, decoder_input_ids=input_ids
|
| 317 |
+
)
|
| 318 |
+
else:
|
| 319 |
+
model_output = self.model(input_ids, output_hidden_states=True)
|
| 320 |
+
if is_chatglm:
|
| 321 |
+
data = (model_output.hidden_states[-1].transpose(0, 1))[0]
|
| 322 |
+
elif is_t5:
|
| 323 |
+
data = model_output.encoder_last_hidden_state[0]
|
| 324 |
+
else:
|
| 325 |
+
data = model_output.hidden_states[-1][0]
|
| 326 |
+
data = F.normalize(torch.mean(data, dim=0), p=2, dim=0)
|
| 327 |
+
embedding.append(data.tolist())
|
| 328 |
+
token_num += len(input_ids[0])
|
| 329 |
+
ret = {
|
| 330 |
+
"embedding": embedding,
|
| 331 |
+
"token_num": token_num,
|
| 332 |
+
}
|
| 333 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 334 |
+
ret = {
|
| 335 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 336 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 337 |
+
}
|
| 338 |
+
except (ValueError, RuntimeError) as e:
|
| 339 |
+
ret = {
|
| 340 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 341 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 342 |
+
}
|
| 343 |
+
return ret
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
app = FastAPI()
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def release_model_semaphore():
|
| 350 |
+
model_semaphore.release()
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def acquire_model_semaphore():
|
| 354 |
+
global model_semaphore, global_counter
|
| 355 |
+
global_counter += 1
|
| 356 |
+
if model_semaphore is None:
|
| 357 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 358 |
+
return model_semaphore.acquire()
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def create_background_tasks():
|
| 362 |
+
background_tasks = BackgroundTasks()
|
| 363 |
+
background_tasks.add_task(release_model_semaphore)
|
| 364 |
+
return background_tasks
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
@app.post("/worker_generate")
|
| 369 |
+
async def api_generate(request: Request):
|
| 370 |
+
params = await request.json()
|
| 371 |
+
await acquire_model_semaphore()
|
| 372 |
+
output = worker.generate_gate(params)
|
| 373 |
+
release_model_semaphore()
|
| 374 |
+
return JSONResponse(output)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@app.post("/worker_get_status")
|
| 378 |
+
async def api_get_status(request: Request):
|
| 379 |
+
return worker.get_status()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@app.post("/model_details")
|
| 386 |
+
async def model_details(request: Request):
|
| 387 |
+
return {"context_length": worker.context_len}
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
if __name__ == "__main__":
|
| 391 |
+
parser = argparse.ArgumentParser()
|
| 392 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 393 |
+
parser.add_argument("--port", type=int, default=21273)
|
| 394 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21273")
|
| 395 |
+
parser.add_argument(
|
| 396 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
parser.add_argument(
|
| 400 |
+
"--sam-path", type=str, default="sam_vit_h_4b8939.pth"
|
| 401 |
+
)
|
| 402 |
+
parser.add_argument(
|
| 403 |
+
"--model-names",
|
| 404 |
+
default="sam",
|
| 405 |
+
type=lambda s: s.split(","),
|
| 406 |
+
help="Optional display comma separated names",
|
| 407 |
+
)
|
| 408 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 409 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 410 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 411 |
+
parser.add_argument("--no-register", action="store_true")
|
| 412 |
+
args = parser.parse_args()
|
| 413 |
+
logger.info(f"args: {args}")
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
worker = ModelWorker(
|
| 417 |
+
args.controller_address,
|
| 418 |
+
args.worker_address,
|
| 419 |
+
worker_id,
|
| 420 |
+
args.no_register,
|
| 421 |
+
args.model_names,
|
| 422 |
+
args.sam_path,
|
| 423 |
+
args.device,
|
| 424 |
+
)
|
| 425 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/seem_test_message.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
import io
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import base64
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torchvision.transforms.functional as F
|
| 18 |
+
|
| 19 |
+
def load_image(image_path):
|
| 20 |
+
img = Image.open(image_path).convert('RGB')
|
| 21 |
+
# import ipdb; ipdb.set_trace()
|
| 22 |
+
# resize if needed
|
| 23 |
+
w, h = img.size
|
| 24 |
+
if max(h, w) > 800:
|
| 25 |
+
if h > w:
|
| 26 |
+
new_h = 800
|
| 27 |
+
new_w = int(w * 800 / h)
|
| 28 |
+
else:
|
| 29 |
+
new_w = 800
|
| 30 |
+
new_h = int(h * 800 / w)
|
| 31 |
+
# import ipdb; ipdb.set_trace()
|
| 32 |
+
img = F.resize(img, (new_h, new_w))
|
| 33 |
+
return img
|
| 34 |
+
|
| 35 |
+
def encode(image: Image):
|
| 36 |
+
buffered = BytesIO()
|
| 37 |
+
image.save(buffered, format="JPEG")
|
| 38 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 39 |
+
return img_b64_str
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
model_name = args.model_name
|
| 44 |
+
|
| 45 |
+
if args.worker_address:
|
| 46 |
+
worker_addr = args.worker_address
|
| 47 |
+
else:
|
| 48 |
+
controller_addr = args.controller_address
|
| 49 |
+
|
| 50 |
+
ret = requests.post(
|
| 51 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 52 |
+
)
|
| 53 |
+
worker_addr = ret.json()["address"]
|
| 54 |
+
print(f"worker_addr: {worker_addr}")
|
| 55 |
+
|
| 56 |
+
if worker_addr == "":
|
| 57 |
+
print(f"No available workers for {model_name}")
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
headers = {"User-Agent": "FastChat Client"}
|
| 61 |
+
if args.send_image:
|
| 62 |
+
img = load_image(args.image_path)
|
| 63 |
+
img_arg = encode(img)
|
| 64 |
+
else:
|
| 65 |
+
img_arg = args.image_path
|
| 66 |
+
datas = {
|
| 67 |
+
"model": model_name,
|
| 68 |
+
"image": img_arg,
|
| 69 |
+
"point": args.point,
|
| 70 |
+
"refimg": img_arg,
|
| 71 |
+
|
| 72 |
+
}
|
| 73 |
+
tic = time.time()
|
| 74 |
+
response = requests.post(
|
| 75 |
+
worker_addr + "/worker_generate",
|
| 76 |
+
headers=headers,
|
| 77 |
+
json=datas,
|
| 78 |
+
)
|
| 79 |
+
toc = time.time()
|
| 80 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 81 |
+
|
| 82 |
+
print("detection result:")
|
| 83 |
+
print(response)
|
| 84 |
+
# response is 'Response' with :
|
| 85 |
+
# ['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
parser = argparse.ArgumentParser()
|
| 91 |
+
# worker parameters
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21043")
|
| 96 |
+
parser.add_argument("--model-name", type=str, default='seem')
|
| 97 |
+
|
| 98 |
+
# model parameters
|
| 99 |
+
# parser.add_argument(
|
| 100 |
+
# "--caption", type=str, default="dogs ."
|
| 101 |
+
# )
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--point", default=[[0.6,0.4]]
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--image_path", type=str,
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--send_image", action="store_true",
|
| 110 |
+
)
|
| 111 |
+
args = parser.parse_args()
|
| 112 |
+
|
| 113 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/seem_worker.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os, io
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import asyncio
|
| 11 |
+
import dataclasses
|
| 12 |
+
import logging
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from typing import List, Tuple, Union
|
| 18 |
+
import threading
|
| 19 |
+
import uuid
|
| 20 |
+
import torchvision
|
| 21 |
+
import numpy as np
|
| 22 |
+
from io import BytesIO
|
| 23 |
+
import base64
|
| 24 |
+
|
| 25 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 26 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 27 |
+
import numpy as np
|
| 28 |
+
import requests
|
| 29 |
+
from PIL import Image
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
import uvicorn
|
| 34 |
+
from torchvision import transforms
|
| 35 |
+
|
| 36 |
+
from modeling.BaseModel import BaseModel
|
| 37 |
+
from modeling import build_model
|
| 38 |
+
from utils.distributed import init_distributed
|
| 39 |
+
from utils.arguments import load_opt_from_config_files
|
| 40 |
+
from utils.constants import COCO_PANOPTIC_CLASSES
|
| 41 |
+
|
| 42 |
+
from demo.seem.tasks.interactive import interactive_infer_image
|
| 43 |
+
|
| 44 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 45 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 46 |
+
|
| 47 |
+
GB = 1 << 30
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
now_file_name = os.__file__
|
| 51 |
+
logdir = "logs/workers/"
|
| 52 |
+
os.makedirs(logdir, exist_ok=True)
|
| 53 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 54 |
+
|
| 55 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 56 |
+
logger = build_logger(now_file_name, logfile)
|
| 57 |
+
global_counter = 0
|
| 58 |
+
|
| 59 |
+
model_semaphore = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def heart_beat_worker(controller):
|
| 63 |
+
while True:
|
| 64 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 65 |
+
controller.send_heart_beat()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
conf_files = "configs/seem/focalt_unicl_lang_demo.yaml"
|
| 69 |
+
opt = load_opt_from_config_files([conf_files])
|
| 70 |
+
opt = init_distributed(opt)
|
| 71 |
+
|
| 72 |
+
def prepare_image(image_pth):
|
| 73 |
+
"""
|
| 74 |
+
apply transformation to the image. crop the image ot 640 short edge by default
|
| 75 |
+
"""
|
| 76 |
+
if os.path.exists(image_pth):
|
| 77 |
+
image = Image.open(image_pth).convert('RGB')
|
| 78 |
+
else:
|
| 79 |
+
image = Image.open(BytesIO(base64.b64decode(image_pth))).convert("RGB")
|
| 80 |
+
|
| 81 |
+
return image
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def prepare_mask(image_pth):
|
| 85 |
+
"""
|
| 86 |
+
apply transformation to the image. crop the image ot 640 short edge by default
|
| 87 |
+
"""
|
| 88 |
+
if os.path.exists(image_pth):
|
| 89 |
+
image = Image.open(image_pth).convert('RGBA')
|
| 90 |
+
else:
|
| 91 |
+
image = Image.open(BytesIO(base64.b64decode(image_pth))).convert("RGBA")
|
| 92 |
+
|
| 93 |
+
return image
|
| 94 |
+
|
| 95 |
+
class ModelWorker:
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
controller_addr,
|
| 99 |
+
worker_addr,
|
| 100 |
+
worker_id,
|
| 101 |
+
model_path,
|
| 102 |
+
model_type,
|
| 103 |
+
model_names
|
| 104 |
+
):
|
| 105 |
+
self.controller_addr = controller_addr
|
| 106 |
+
self.worker_addr = worker_addr
|
| 107 |
+
self.worker_id = worker_id
|
| 108 |
+
if model_path.endswith("/"):
|
| 109 |
+
model_path = model_path[:-1]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
logger.info(f"Loading the model on worker {worker_id} ...")
|
| 113 |
+
self.model_path = model_path
|
| 114 |
+
self.model_type = model_type
|
| 115 |
+
self.model_names = model_names
|
| 116 |
+
|
| 117 |
+
# load model
|
| 118 |
+
self.model = self.build_model()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
self.register_to_controller()
|
| 123 |
+
self.heart_beat_thread = threading.Thread(
|
| 124 |
+
target=heart_beat_worker, args=(self,)
|
| 125 |
+
)
|
| 126 |
+
self.heart_beat_thread.start()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def build_model(self):
|
| 130 |
+
# META DATA
|
| 131 |
+
cur_model = 'None'
|
| 132 |
+
if 'focalt' in conf_files:
|
| 133 |
+
pretrained_pth = os.path.join("seem_focalt_v0.pt")
|
| 134 |
+
if not os.path.exists(pretrained_pth):
|
| 135 |
+
os.system("wget {}".format(
|
| 136 |
+
"https://huggingface.co/xdecoder/SEEM/resolve/main/seem_focalt_v0.pt"))
|
| 137 |
+
cur_model = 'Focal-T'
|
| 138 |
+
elif 'focal' in conf_files:
|
| 139 |
+
pretrained_pth = os.path.join("seem_focall_v0.pt")
|
| 140 |
+
if not os.path.exists(pretrained_pth):
|
| 141 |
+
os.system("wget {}".format(
|
| 142 |
+
"https://huggingface.co/xdecoder/SEEM/resolve/main/seem_focall_v0.pt"))
|
| 143 |
+
cur_model = 'Focal-L'
|
| 144 |
+
|
| 145 |
+
'''
|
| 146 |
+
build model
|
| 147 |
+
'''
|
| 148 |
+
model = BaseModel(opt, build_model(opt)).from_pretrained(
|
| 149 |
+
pretrained_pth).eval().cuda()
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
model.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(
|
| 152 |
+
COCO_PANOPTIC_CLASSES + ["background"], is_eval=True)
|
| 153 |
+
return model
|
| 154 |
+
|
| 155 |
+
def register_to_controller(self):
|
| 156 |
+
logger.info("Register to controller")
|
| 157 |
+
|
| 158 |
+
url = self.controller_addr + "/register_worker"
|
| 159 |
+
data = {
|
| 160 |
+
"worker_name": self.worker_addr,
|
| 161 |
+
"check_heart_beat": True,
|
| 162 |
+
"worker_status": self.get_status(),
|
| 163 |
+
}
|
| 164 |
+
r = requests.post(url, json=data)
|
| 165 |
+
assert r.status_code == 200
|
| 166 |
+
|
| 167 |
+
def send_heart_beat(self):
|
| 168 |
+
logger.info(
|
| 169 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 170 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 171 |
+
f"global_counter: {global_counter}. "
|
| 172 |
+
f"worker_id: {worker_id}. "
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 176 |
+
|
| 177 |
+
while True:
|
| 178 |
+
try:
|
| 179 |
+
ret = requests.post(
|
| 180 |
+
url,
|
| 181 |
+
json={
|
| 182 |
+
"worker_name": self.worker_addr,
|
| 183 |
+
"queue_length": self.get_queue_length(),
|
| 184 |
+
},
|
| 185 |
+
timeout=5,
|
| 186 |
+
)
|
| 187 |
+
exist = ret.json()["exist"]
|
| 188 |
+
break
|
| 189 |
+
except requests.exceptions.RequestException as e:
|
| 190 |
+
logger.error(f"heart beat error: {e}")
|
| 191 |
+
time.sleep(5)
|
| 192 |
+
|
| 193 |
+
if not exist:
|
| 194 |
+
self.register_to_controller()
|
| 195 |
+
|
| 196 |
+
def get_queue_length(self):
|
| 197 |
+
if (
|
| 198 |
+
model_semaphore is None
|
| 199 |
+
or model_semaphore._value is None
|
| 200 |
+
or model_semaphore._waiters is None
|
| 201 |
+
):
|
| 202 |
+
return 0
|
| 203 |
+
else:
|
| 204 |
+
return (
|
| 205 |
+
args.limit_model_concurrency
|
| 206 |
+
- model_semaphore._value
|
| 207 |
+
+ len(model_semaphore._waiters)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def get_status(self):
|
| 211 |
+
return {
|
| 212 |
+
"model_names": self.model_names,
|
| 213 |
+
"speed": 1,
|
| 214 |
+
"queue_length": self.get_queue_length(),
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def generate_stream_func(self, model_path, model_type, params):
|
| 219 |
+
|
| 220 |
+
image_path = params["image"]
|
| 221 |
+
pil_image = prepare_image(image_path)
|
| 222 |
+
|
| 223 |
+
refimg_path = params["refimg"]
|
| 224 |
+
pil_refimg = prepare_image(refimg_path)
|
| 225 |
+
|
| 226 |
+
refmask_path = params["refmask"]
|
| 227 |
+
pil_refmask = prepare_mask(refmask_path)
|
| 228 |
+
|
| 229 |
+
image_input = {
|
| 230 |
+
'image': pil_image,
|
| 231 |
+
"mask": None,
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
refimg_input = {
|
| 235 |
+
'image': pil_refimg,
|
| 236 |
+
"mask": pil_refmask,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
res_img = interactive_infer_image(self.model, None, image_input, 'Example', refimg=refimg_input)[0]
|
| 240 |
+
|
| 241 |
+
# to b64
|
| 242 |
+
buffered = BytesIO()
|
| 243 |
+
res_img.save(buffered, format="JPEG")
|
| 244 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 245 |
+
|
| 246 |
+
pred_dict = {
|
| 247 |
+
"edited_image": img_b64_str
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
return pred_dict
|
| 251 |
+
|
| 252 |
+
def generate_gate(self, params):
|
| 253 |
+
# ret = {"text": "", "error_code": 0}
|
| 254 |
+
# ret = self.generate_stream_func(
|
| 255 |
+
# self.model_path,
|
| 256 |
+
# self.model_type,
|
| 257 |
+
# params
|
| 258 |
+
# )
|
| 259 |
+
try:
|
| 260 |
+
|
| 261 |
+
ret = {"text": "", "error_code": 0}
|
| 262 |
+
ret = self.generate_stream_func(
|
| 263 |
+
self.model_path,
|
| 264 |
+
self.model_type,
|
| 265 |
+
params
|
| 266 |
+
)
|
| 267 |
+
# except torch.cuda.OutOfMemoryError as e:
|
| 268 |
+
# ret = {
|
| 269 |
+
# "text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 270 |
+
# "error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 271 |
+
# }
|
| 272 |
+
except (ValueError, RuntimeError) as e:
|
| 273 |
+
ret = {
|
| 274 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 275 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 276 |
+
}
|
| 277 |
+
return ret
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
app = FastAPI()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def release_model_semaphore():
|
| 284 |
+
model_semaphore.release()
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def acquire_model_semaphore():
|
| 288 |
+
global model_semaphore, global_counter
|
| 289 |
+
global_counter += 1
|
| 290 |
+
if model_semaphore is None:
|
| 291 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 292 |
+
return model_semaphore.acquire()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def create_background_tasks():
|
| 296 |
+
background_tasks = BackgroundTasks()
|
| 297 |
+
background_tasks.add_task(release_model_semaphore)
|
| 298 |
+
return background_tasks
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@app.post("/worker_generate")
|
| 303 |
+
async def api_generate(request: Request):
|
| 304 |
+
params = await request.json()
|
| 305 |
+
await acquire_model_semaphore()
|
| 306 |
+
output = worker.generate_gate(params)
|
| 307 |
+
release_model_semaphore()
|
| 308 |
+
return JSONResponse(output)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@app.post("/worker_get_status")
|
| 312 |
+
async def api_get_status(request: Request):
|
| 313 |
+
return worker.get_status()
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@app.post("/model_details")
|
| 320 |
+
async def model_details(request: Request):
|
| 321 |
+
return {"context_length": worker.context_len}
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
if __name__ == "__main__":
|
| 325 |
+
parser = argparse.ArgumentParser()
|
| 326 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 327 |
+
parser.add_argument("--port", type=int, default=21043)
|
| 328 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21043")
|
| 329 |
+
parser.add_argument(
|
| 330 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
parser.add_argument(
|
| 334 |
+
"--model-path", type=str, default="/comp_robot/lifeng/code/Semantic-SAM-worker/ckp/swint_only_sam_many2many.pth"
|
| 335 |
+
)
|
| 336 |
+
parser.add_argument(
|
| 337 |
+
"--model-type", type=str, default="T"
|
| 338 |
+
)
|
| 339 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 340 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 341 |
+
args = parser.parse_args()
|
| 342 |
+
logger.info(f"args: {args}")
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
worker = ModelWorker(
|
| 346 |
+
args.controller_address,
|
| 347 |
+
args.worker_address,
|
| 348 |
+
worker_id,
|
| 349 |
+
args.model_path,
|
| 350 |
+
args.model_type,
|
| 351 |
+
['seem']
|
| 352 |
+
)
|
| 353 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/semantic_sam_worker.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os, io
|
| 5 |
+
|
| 6 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 7 |
+
from semantic_sam import plot_multi_results, build_semantic_sam, SemanticSAMPredictor
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import asyncio
|
| 11 |
+
import dataclasses
|
| 12 |
+
import logging
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from typing import List, Tuple, Union
|
| 18 |
+
import threading
|
| 19 |
+
import uuid
|
| 20 |
+
import torchvision
|
| 21 |
+
import numpy as np
|
| 22 |
+
from io import BytesIO
|
| 23 |
+
import base64
|
| 24 |
+
|
| 25 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 26 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 27 |
+
import numpy as np
|
| 28 |
+
import requests
|
| 29 |
+
from PIL import Image
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
import uvicorn
|
| 34 |
+
from torchvision import transforms
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 38 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 39 |
+
|
| 40 |
+
GB = 1 << 30
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
now_file_name = os.__file__
|
| 44 |
+
logdir = "logs/workers/"
|
| 45 |
+
os.makedirs(logdir, exist_ok=True)
|
| 46 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 47 |
+
|
| 48 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 49 |
+
logger = build_logger(now_file_name, logfile)
|
| 50 |
+
global_counter = 0
|
| 51 |
+
|
| 52 |
+
model_semaphore = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def heart_beat_worker(controller):
|
| 56 |
+
while True:
|
| 57 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 58 |
+
controller.send_heart_beat()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def prepare_image(image_pth):
|
| 62 |
+
"""
|
| 63 |
+
apply transformation to the image. crop the image ot 640 short edge by default
|
| 64 |
+
"""
|
| 65 |
+
if os.path.exists(image_pth):
|
| 66 |
+
image = Image.open(image_pth).convert('RGB')
|
| 67 |
+
else:
|
| 68 |
+
image = Image.open(BytesIO(base64.b64decode(image_pth))).convert("RGB")
|
| 69 |
+
t = []
|
| 70 |
+
t.append(transforms.Resize(640, interpolation=Image.BICUBIC))
|
| 71 |
+
transform1 = transforms.Compose(t)
|
| 72 |
+
image_ori = transform1(image)
|
| 73 |
+
|
| 74 |
+
image_ori = np.asarray(image_ori)
|
| 75 |
+
images = torch.from_numpy(image_ori.copy()).permute(2, 0, 1).cuda()
|
| 76 |
+
|
| 77 |
+
return image_ori, images
|
| 78 |
+
|
| 79 |
+
class ModelWorker:
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
controller_addr,
|
| 83 |
+
worker_addr,
|
| 84 |
+
worker_id,
|
| 85 |
+
model_path,
|
| 86 |
+
model_type,
|
| 87 |
+
model_names
|
| 88 |
+
):
|
| 89 |
+
self.controller_addr = controller_addr
|
| 90 |
+
self.worker_addr = worker_addr
|
| 91 |
+
self.worker_id = worker_id
|
| 92 |
+
if model_path.endswith("/"):
|
| 93 |
+
model_path = model_path[:-1]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
logger.info(f"Loading the model on worker {worker_id} ...")
|
| 97 |
+
self.model_path = model_path
|
| 98 |
+
self.model_type = model_type
|
| 99 |
+
self.model_names = model_names
|
| 100 |
+
|
| 101 |
+
self.register_to_controller()
|
| 102 |
+
self.heart_beat_thread = threading.Thread(
|
| 103 |
+
target=heart_beat_worker, args=(self,)
|
| 104 |
+
)
|
| 105 |
+
self.heart_beat_thread.start()
|
| 106 |
+
|
| 107 |
+
def register_to_controller(self):
|
| 108 |
+
logger.info("Register to controller")
|
| 109 |
+
|
| 110 |
+
url = self.controller_addr + "/register_worker"
|
| 111 |
+
data = {
|
| 112 |
+
"worker_name": self.worker_addr,
|
| 113 |
+
"check_heart_beat": True,
|
| 114 |
+
"worker_status": self.get_status(),
|
| 115 |
+
}
|
| 116 |
+
r = requests.post(url, json=data)
|
| 117 |
+
assert r.status_code == 200
|
| 118 |
+
|
| 119 |
+
def send_heart_beat(self):
|
| 120 |
+
logger.info(
|
| 121 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 122 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 123 |
+
f"global_counter: {global_counter}. "
|
| 124 |
+
f"worker_id: {worker_id}. "
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 128 |
+
|
| 129 |
+
while True:
|
| 130 |
+
try:
|
| 131 |
+
ret = requests.post(
|
| 132 |
+
url,
|
| 133 |
+
json={
|
| 134 |
+
"worker_name": self.worker_addr,
|
| 135 |
+
"queue_length": self.get_queue_length(),
|
| 136 |
+
},
|
| 137 |
+
timeout=5,
|
| 138 |
+
)
|
| 139 |
+
exist = ret.json()["exist"]
|
| 140 |
+
break
|
| 141 |
+
except requests.exceptions.RequestException as e:
|
| 142 |
+
logger.error(f"heart beat error: {e}")
|
| 143 |
+
time.sleep(5)
|
| 144 |
+
|
| 145 |
+
if not exist:
|
| 146 |
+
self.register_to_controller()
|
| 147 |
+
|
| 148 |
+
def get_queue_length(self):
|
| 149 |
+
if (
|
| 150 |
+
model_semaphore is None
|
| 151 |
+
or model_semaphore._value is None
|
| 152 |
+
or model_semaphore._waiters is None
|
| 153 |
+
):
|
| 154 |
+
return 0
|
| 155 |
+
else:
|
| 156 |
+
return (
|
| 157 |
+
args.limit_model_concurrency
|
| 158 |
+
- model_semaphore._value
|
| 159 |
+
+ len(model_semaphore._waiters)
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def get_status(self):
|
| 163 |
+
return {
|
| 164 |
+
"model_names": self.model_names,
|
| 165 |
+
"speed": 1,
|
| 166 |
+
"queue_length": self.get_queue_length(),
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def generate_stream_func(self,model_path,model_type, params):
|
| 171 |
+
# get inputs
|
| 172 |
+
if 'point' in params:
|
| 173 |
+
point_prompt = params["point"]
|
| 174 |
+
else:
|
| 175 |
+
assert 'boxes' in params
|
| 176 |
+
box_prompt = params["boxes"]
|
| 177 |
+
# centers
|
| 178 |
+
point_prompt = []
|
| 179 |
+
for box in box_prompt:
|
| 180 |
+
point_prompt.append([(box[0]+box[2])/2, (box[1]+box[3])/2])
|
| 181 |
+
image_path = params["image"]
|
| 182 |
+
model_type = model_type
|
| 183 |
+
model_ckpt = model_path
|
| 184 |
+
# model_name = params["model"]
|
| 185 |
+
|
| 186 |
+
# load image and run models
|
| 187 |
+
original_image, input_image = prepare_image(image_path) # change the image path to your image
|
| 188 |
+
mask_generator = SemanticSAMPredictor(build_semantic_sam(model_type=model_type, ckpt=model_ckpt)) # model_type: 'L' / 'T', depends on your checkpint
|
| 189 |
+
iou_sort_masks, area_sort_masks = mask_generator.predict_masks(original_image, input_image, point=point_prompt) # input point [[w, h]] relative location, i.e, [[0.5, 0.5]] is the center of the image
|
| 190 |
+
|
| 191 |
+
# 创建一个BytesIO对象,用于临时存储图像数据
|
| 192 |
+
image_data = io.BytesIO()
|
| 193 |
+
sum_0=np.array(iou_sort_masks[0]).sum()
|
| 194 |
+
sum_1=np.array(iou_sort_masks[1]).sum()
|
| 195 |
+
mask_List = []
|
| 196 |
+
# 将图像保存到BytesIO对象中,格式为JPEG
|
| 197 |
+
for mask in iou_sort_masks :
|
| 198 |
+
image_data = io.BytesIO()
|
| 199 |
+
mask.save(image_data, format='JPEG')
|
| 200 |
+
# 将BytesIO对象的内容转换为字节串
|
| 201 |
+
image_data_bytes = image_data.getvalue()
|
| 202 |
+
# 将图像数据编码为Base64字符串
|
| 203 |
+
encoded_image = base64.b64encode(image_data_bytes).decode('utf-8')
|
| 204 |
+
|
| 205 |
+
mask_List.append(encoded_image)
|
| 206 |
+
|
| 207 |
+
pred_dict = {
|
| 208 |
+
"iou_sort_masks": mask_List
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
return pred_dict
|
| 212 |
+
|
| 213 |
+
def generate_gate(self, params):
|
| 214 |
+
try:
|
| 215 |
+
|
| 216 |
+
ret = {"text": "", "error_code": 0}
|
| 217 |
+
ret = self.generate_stream_func(
|
| 218 |
+
self.model_path,
|
| 219 |
+
self.model_type,
|
| 220 |
+
params
|
| 221 |
+
)
|
| 222 |
+
# except torch.cuda.OutOfMemoryError as e:
|
| 223 |
+
# ret = {
|
| 224 |
+
# "text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 225 |
+
# "error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 226 |
+
# }
|
| 227 |
+
except (ValueError, RuntimeError) as e:
|
| 228 |
+
ret = {
|
| 229 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 230 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 231 |
+
}
|
| 232 |
+
return ret
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
app = FastAPI()
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def release_model_semaphore():
|
| 239 |
+
model_semaphore.release()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def acquire_model_semaphore():
|
| 243 |
+
global model_semaphore, global_counter
|
| 244 |
+
global_counter += 1
|
| 245 |
+
if model_semaphore is None:
|
| 246 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 247 |
+
return model_semaphore.acquire()
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def create_background_tasks():
|
| 251 |
+
background_tasks = BackgroundTasks()
|
| 252 |
+
background_tasks.add_task(release_model_semaphore)
|
| 253 |
+
return background_tasks
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@app.post("/worker_generate")
|
| 258 |
+
async def api_generate(request: Request):
|
| 259 |
+
params = await request.json()
|
| 260 |
+
await acquire_model_semaphore()
|
| 261 |
+
output = worker.generate_gate(params)
|
| 262 |
+
release_model_semaphore()
|
| 263 |
+
return JSONResponse(output)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.post("/worker_get_status")
|
| 267 |
+
async def api_get_status(request: Request):
|
| 268 |
+
return worker.get_status()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@app.post("/model_details")
|
| 275 |
+
async def model_details(request: Request):
|
| 276 |
+
return {"context_length": worker.context_len}
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
| 280 |
+
parser = argparse.ArgumentParser()
|
| 281 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 282 |
+
parser.add_argument("--port", type=int, default=21004)
|
| 283 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21004")
|
| 284 |
+
parser.add_argument(
|
| 285 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
parser.add_argument(
|
| 289 |
+
"--model-path", type=str, default="/comp_robot/lifeng/code/Semantic-SAM-worker/ckp/swint_only_sam_many2many.pth"
|
| 290 |
+
)
|
| 291 |
+
parser.add_argument(
|
| 292 |
+
"--model-type", type=str, default="T"
|
| 293 |
+
)
|
| 294 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 295 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 296 |
+
args = parser.parse_args()
|
| 297 |
+
logger.info(f"args: {args}")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
worker = ModelWorker(
|
| 301 |
+
args.controller_address,
|
| 302 |
+
args.worker_address,
|
| 303 |
+
worker_id,
|
| 304 |
+
args.model_path,
|
| 305 |
+
args.model_type,
|
| 306 |
+
['semantic_sam', 'semantic-sam']
|
| 307 |
+
)
|
| 308 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/stablediffusion_test_message.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Send a test message."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import base64
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torchvision.transforms.functional as F
|
| 16 |
+
|
| 17 |
+
def load_image(image_path):
|
| 18 |
+
img = Image.open(image_path).convert('RGB')
|
| 19 |
+
# import ipdb; ipdb.set_trace()
|
| 20 |
+
# resize if needed
|
| 21 |
+
w, h = img.size
|
| 22 |
+
if max(h, w) > 800:
|
| 23 |
+
if h > w:
|
| 24 |
+
new_h = 800
|
| 25 |
+
new_w = int(w * 800 / h)
|
| 26 |
+
else:
|
| 27 |
+
new_w = 800
|
| 28 |
+
new_h = int(h * 800 / w)
|
| 29 |
+
# import ipdb; ipdb.set_trace()
|
| 30 |
+
img = F.resize(img, (new_h, new_w))
|
| 31 |
+
return img
|
| 32 |
+
|
| 33 |
+
def encode(image: Image):
|
| 34 |
+
buffered = BytesIO()
|
| 35 |
+
image.save(buffered, format="JPEG")
|
| 36 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 37 |
+
return img_b64_str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
model_name = args.model_name
|
| 42 |
+
|
| 43 |
+
if args.worker_address:
|
| 44 |
+
worker_addr = args.worker_address
|
| 45 |
+
else:
|
| 46 |
+
controller_addr = args.controller_address
|
| 47 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 48 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 49 |
+
models = ret.json()["models"]
|
| 50 |
+
models.sort()
|
| 51 |
+
print(f"Models: {models}")
|
| 52 |
+
|
| 53 |
+
ret = requests.post(
|
| 54 |
+
controller_addr + "/get_worker_address", json={"model": model_name}
|
| 55 |
+
)
|
| 56 |
+
worker_addr = ret.json()["address"]
|
| 57 |
+
print(f"worker_addr: {worker_addr}")
|
| 58 |
+
|
| 59 |
+
if worker_addr == "":
|
| 60 |
+
print(f"No available workers for {model_name}")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
headers = {"User-Agent": "GSAM Client"}
|
| 64 |
+
datas = {
|
| 65 |
+
"model": model_name,
|
| 66 |
+
"prompt": "a photo of a cat"
|
| 67 |
+
}
|
| 68 |
+
tic = time.time()
|
| 69 |
+
response = requests.post(
|
| 70 |
+
worker_addr + "/worker_generate",
|
| 71 |
+
headers=headers,
|
| 72 |
+
json=datas,
|
| 73 |
+
)
|
| 74 |
+
toc = time.time()
|
| 75 |
+
print(f"Time: {toc - tic:.3f}s")
|
| 76 |
+
|
| 77 |
+
print("detection result:")
|
| 78 |
+
print(response.json())
|
| 79 |
+
res = response.json()
|
| 80 |
+
|
| 81 |
+
image = Image.open(BytesIO(base64.b64decode(res['edited_image']))).convert("RGB")
|
| 82 |
+
# save
|
| 83 |
+
image.save("demo2_edited2.jpg")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
parser = argparse.ArgumentParser()
|
| 92 |
+
# worker parameters
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 95 |
+
)
|
| 96 |
+
parser.add_argument("--worker-address", type=str)
|
| 97 |
+
parser.add_argument("--model-name", type=str, default='sd')
|
| 98 |
+
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--send_image", action="store_true",
|
| 101 |
+
)
|
| 102 |
+
args = parser.parse_args()
|
| 103 |
+
|
| 104 |
+
main()
|
fin-mm/code/LLaVA-Plus/serve/stablediffusion_worker.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
import sys, os
|
| 5 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import asyncio
|
| 9 |
+
import dataclasses
|
| 10 |
+
import logging
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from typing import List, Tuple, Union
|
| 16 |
+
import threading
|
| 17 |
+
import uuid
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
import base64
|
| 21 |
+
|
| 22 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 23 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 24 |
+
import numpy as np
|
| 25 |
+
import requests
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from diffusers import StableDiffusionPipeline, EulerAncestralDiscreteScheduler
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from transformers import (
|
| 32 |
+
AutoTokenizer,
|
| 33 |
+
AutoModelForCausalLM,
|
| 34 |
+
LlamaTokenizer,
|
| 35 |
+
AutoModel,
|
| 36 |
+
)
|
| 37 |
+
except ImportError:
|
| 38 |
+
from transformers import (
|
| 39 |
+
AutoTokenizer,
|
| 40 |
+
AutoModelForCausalLM,
|
| 41 |
+
LLaMATokenizer,
|
| 42 |
+
AutoModel,
|
| 43 |
+
)
|
| 44 |
+
from transformers import AutoProcessor, Blip2ForConditionalGeneration
|
| 45 |
+
|
| 46 |
+
import torch
|
| 47 |
+
import torch.nn.functional as F
|
| 48 |
+
import uvicorn
|
| 49 |
+
|
| 50 |
+
from serve.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG
|
| 51 |
+
from serve.utils import build_logger, pretty_print_semaphore
|
| 52 |
+
|
| 53 |
+
GB = 1 << 30
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
now_file_name = os.__file__
|
| 57 |
+
logdir = "logs/workers/"
|
| 58 |
+
os.makedirs(logdir, exist_ok=True)
|
| 59 |
+
logfile = os.path.join(logdir, f"{now_file_name}.log")
|
| 60 |
+
|
| 61 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 62 |
+
logger = build_logger(now_file_name, logfile)
|
| 63 |
+
global_counter = 0
|
| 64 |
+
|
| 65 |
+
model_semaphore = None
|
| 66 |
+
|
| 67 |
+
def encode(image: Image):
|
| 68 |
+
buffered = BytesIO()
|
| 69 |
+
image.save(buffered, format="JPEG")
|
| 70 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 71 |
+
return img_b64_str
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def heart_beat_worker(controller):
|
| 75 |
+
while True:
|
| 76 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 77 |
+
controller.send_heart_beat()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ModelWorker:
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
controller_addr,
|
| 84 |
+
worker_addr,
|
| 85 |
+
worker_id,
|
| 86 |
+
no_register,
|
| 87 |
+
model_path,
|
| 88 |
+
model_names,
|
| 89 |
+
device,
|
| 90 |
+
):
|
| 91 |
+
self.controller_addr = controller_addr
|
| 92 |
+
self.worker_addr = worker_addr
|
| 93 |
+
self.worker_id = worker_id
|
| 94 |
+
self.model_names = model_names
|
| 95 |
+
self.device = device
|
| 96 |
+
|
| 97 |
+
# # load model
|
| 98 |
+
# logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
|
| 99 |
+
# self.processor = AutoProcessor.from_pretrained(model_path)
|
| 100 |
+
# self.model = Blip2ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16)
|
| 101 |
+
# self.model.eval()
|
| 102 |
+
# self.model.to(device)
|
| 103 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
| 104 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
| 105 |
+
pipe.to("cuda")
|
| 106 |
+
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
| 107 |
+
|
| 108 |
+
self.pipe = pipe
|
| 109 |
+
|
| 110 |
+
if not no_register:
|
| 111 |
+
self.register_to_controller()
|
| 112 |
+
self.heart_beat_thread = threading.Thread(
|
| 113 |
+
target=heart_beat_worker, args=(self,)
|
| 114 |
+
)
|
| 115 |
+
self.heart_beat_thread.start()
|
| 116 |
+
|
| 117 |
+
def resize(self, image:Image, resize_w:int, resize_h:int):
|
| 118 |
+
image = image.resize((resize_w, resize_h))
|
| 119 |
+
return image
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def register_to_controller(self):
|
| 123 |
+
logger.info("Register to controller")
|
| 124 |
+
|
| 125 |
+
url = self.controller_addr + "/register_worker"
|
| 126 |
+
data = {
|
| 127 |
+
"worker_name": self.worker_addr,
|
| 128 |
+
"check_heart_beat": True,
|
| 129 |
+
"worker_status": self.get_status(),
|
| 130 |
+
}
|
| 131 |
+
r = requests.post(url, json=data)
|
| 132 |
+
assert r.status_code == 200
|
| 133 |
+
|
| 134 |
+
def send_heart_beat(self):
|
| 135 |
+
logger.info(
|
| 136 |
+
f"Send heart beat. Models: {self.model_names}. "
|
| 137 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 138 |
+
f"global_counter: {global_counter}. "
|
| 139 |
+
f"worker_id: {worker_id}. "
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 143 |
+
|
| 144 |
+
while True:
|
| 145 |
+
try:
|
| 146 |
+
ret = requests.post(
|
| 147 |
+
url,
|
| 148 |
+
json={
|
| 149 |
+
"worker_name": self.worker_addr,
|
| 150 |
+
"queue_length": self.get_queue_length(),
|
| 151 |
+
},
|
| 152 |
+
timeout=5,
|
| 153 |
+
)
|
| 154 |
+
exist = ret.json()["exist"]
|
| 155 |
+
break
|
| 156 |
+
except requests.exceptions.RequestException as e:
|
| 157 |
+
logger.error(f"heart beat error: {e}")
|
| 158 |
+
time.sleep(5)
|
| 159 |
+
|
| 160 |
+
if not exist:
|
| 161 |
+
self.register_to_controller()
|
| 162 |
+
|
| 163 |
+
def get_queue_length(self):
|
| 164 |
+
if (
|
| 165 |
+
model_semaphore is None
|
| 166 |
+
or model_semaphore._value is None
|
| 167 |
+
or model_semaphore._waiters is None
|
| 168 |
+
):
|
| 169 |
+
return 0
|
| 170 |
+
else:
|
| 171 |
+
return (
|
| 172 |
+
args.limit_model_concurrency
|
| 173 |
+
- model_semaphore._value
|
| 174 |
+
+ len(model_semaphore._waiters)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def get_status(self):
|
| 178 |
+
return {
|
| 179 |
+
"model_names": self.model_names,
|
| 180 |
+
"speed": 1,
|
| 181 |
+
"queue_length": self.get_queue_length(),
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def generate_stream_func(self, model, params, device):
|
| 185 |
+
prompt = params["prompt"]
|
| 186 |
+
|
| 187 |
+
# run
|
| 188 |
+
images = self.pipe(prompt, num_inference_steps=20).images
|
| 189 |
+
image = images[0]
|
| 190 |
+
|
| 191 |
+
# save image
|
| 192 |
+
# images[0].save("test.jpg")
|
| 193 |
+
|
| 194 |
+
pred_dict = {
|
| 195 |
+
"edited_image": encode(image),
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
return pred_dict
|
| 199 |
+
|
| 200 |
+
def generate_gate(self, params):
|
| 201 |
+
try:
|
| 202 |
+
|
| 203 |
+
ret = {"text": "", "error_code": 0}
|
| 204 |
+
ret = self.generate_stream_func(
|
| 205 |
+
None,
|
| 206 |
+
params,
|
| 207 |
+
self.device,
|
| 208 |
+
)
|
| 209 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 210 |
+
ret = {
|
| 211 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 212 |
+
"error_code": ErrorCode.CUDA_OUT_OF_MEMORY,
|
| 213 |
+
}
|
| 214 |
+
except (ValueError, RuntimeError) as e:
|
| 215 |
+
ret = {
|
| 216 |
+
"text": f"{SERVER_ERROR_MSG}\n\n({e})",
|
| 217 |
+
"error_code": ErrorCode.INTERNAL_ERROR,
|
| 218 |
+
}
|
| 219 |
+
return ret
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
app = FastAPI()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def release_model_semaphore():
|
| 227 |
+
model_semaphore.release()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def acquire_model_semaphore():
|
| 231 |
+
global model_semaphore, global_counter
|
| 232 |
+
global_counter += 1
|
| 233 |
+
if model_semaphore is None:
|
| 234 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 235 |
+
return model_semaphore.acquire()
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def create_background_tasks():
|
| 239 |
+
background_tasks = BackgroundTasks()
|
| 240 |
+
background_tasks.add_task(release_model_semaphore)
|
| 241 |
+
return background_tasks
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@app.post("/worker_generate")
|
| 246 |
+
async def api_generate(request: Request):
|
| 247 |
+
params = await request.json()
|
| 248 |
+
await acquire_model_semaphore()
|
| 249 |
+
output = worker.generate_gate(params)
|
| 250 |
+
release_model_semaphore()
|
| 251 |
+
return JSONResponse(output)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@app.post("/worker_get_status")
|
| 255 |
+
async def api_get_status(request: Request):
|
| 256 |
+
return worker.get_status()
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@app.post("/model_details")
|
| 263 |
+
async def model_details(request: Request):
|
| 264 |
+
return {"context_length": worker.context_len}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
parser = argparse.ArgumentParser()
|
| 269 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 270 |
+
parser.add_argument("--port", type=int, default=21307)
|
| 271 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21307")
|
| 272 |
+
parser.add_argument(
|
| 273 |
+
"--controller-address", type=str, default="http://localhost:21001"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
parser.add_argument(
|
| 277 |
+
"--model-path", type=str, default="Salesforce/blip2-opt-2.7b"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--model-names",
|
| 282 |
+
default="stable-diffusion,sd",
|
| 283 |
+
type=lambda s: s.split(","),
|
| 284 |
+
help="Optional display comma separated names",
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 287 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 288 |
+
parser.add_argument("--stream-interval", type=int, default=2)
|
| 289 |
+
parser.add_argument("--no-register", action="store_true")
|
| 290 |
+
args = parser.parse_args()
|
| 291 |
+
logger.info(f"args: {args}")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
worker = ModelWorker(
|
| 295 |
+
args.controller_address,
|
| 296 |
+
args.worker_address,
|
| 297 |
+
worker_id,
|
| 298 |
+
args.no_register,
|
| 299 |
+
args.model_path,
|
| 300 |
+
args.model_names,
|
| 301 |
+
args.device,
|
| 302 |
+
)
|
| 303 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
fin-mm/code/LLaVA-Plus/serve/utils.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Common utilities.
|
| 3 |
+
"""
|
| 4 |
+
from asyncio import AbstractEventLoop
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import logging.handlers
|
| 8 |
+
import os
|
| 9 |
+
import platform
|
| 10 |
+
import sys
|
| 11 |
+
from typing import AsyncGenerator, Generator
|
| 12 |
+
import warnings
|
| 13 |
+
|
| 14 |
+
import requests
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from serve.constants import LOGDIR
|
| 18 |
+
|
| 19 |
+
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
| 20 |
+
|
| 21 |
+
handler = None
|
| 22 |
+
visited_loggers = set()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build_logger(logger_name, logger_filename):
|
| 26 |
+
global handler
|
| 27 |
+
|
| 28 |
+
formatter = logging.Formatter(
|
| 29 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
| 30 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Set the format of root handlers
|
| 34 |
+
if not logging.getLogger().handlers:
|
| 35 |
+
if sys.version_info[1] >= 9:
|
| 36 |
+
# This is for windows
|
| 37 |
+
logging.basicConfig(level=logging.INFO, encoding="utf-8")
|
| 38 |
+
else:
|
| 39 |
+
if platform.system() == "Windows":
|
| 40 |
+
warnings.warn(
|
| 41 |
+
"If you are running on Windows, "
|
| 42 |
+
"we recommend you use Python >= 3.9 for UTF-8 encoding."
|
| 43 |
+
)
|
| 44 |
+
logging.basicConfig(level=logging.INFO)
|
| 45 |
+
logging.getLogger().handlers[0].setFormatter(formatter)
|
| 46 |
+
|
| 47 |
+
# Redirect stdout and stderr to loggers
|
| 48 |
+
stdout_logger = logging.getLogger("stdout")
|
| 49 |
+
stdout_logger.setLevel(logging.INFO)
|
| 50 |
+
sl = StreamToLogger(stdout_logger, logging.INFO)
|
| 51 |
+
sys.stdout = sl
|
| 52 |
+
|
| 53 |
+
stderr_logger = logging.getLogger("stderr")
|
| 54 |
+
stderr_logger.setLevel(logging.ERROR)
|
| 55 |
+
sl = StreamToLogger(stderr_logger, logging.ERROR)
|
| 56 |
+
sys.stderr = sl
|
| 57 |
+
|
| 58 |
+
# Get logger
|
| 59 |
+
logger = logging.getLogger(logger_name)
|
| 60 |
+
logger.setLevel(logging.INFO)
|
| 61 |
+
|
| 62 |
+
os.makedirs(LOGDIR, exist_ok=True)
|
| 63 |
+
filename = os.path.join(LOGDIR, logger_filename)
|
| 64 |
+
handler = logging.handlers.TimedRotatingFileHandler(
|
| 65 |
+
filename, when="D", utc=True, encoding="utf-8"
|
| 66 |
+
)
|
| 67 |
+
handler.setFormatter(formatter)
|
| 68 |
+
|
| 69 |
+
for logger in [stdout_logger, stderr_logger, logger]:
|
| 70 |
+
if logger in visited_loggers:
|
| 71 |
+
continue
|
| 72 |
+
visited_loggers.add(logger)
|
| 73 |
+
logger.addHandler(handler)
|
| 74 |
+
|
| 75 |
+
return logger
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class StreamToLogger(object):
|
| 79 |
+
"""
|
| 80 |
+
Fake file-like stream object that redirects writes to a logger instance.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, logger, log_level=logging.INFO):
|
| 84 |
+
self.terminal = sys.stdout
|
| 85 |
+
self.logger = logger
|
| 86 |
+
self.log_level = log_level
|
| 87 |
+
self.linebuf = ""
|
| 88 |
+
|
| 89 |
+
def __getattr__(self, attr):
|
| 90 |
+
return getattr(self.terminal, attr)
|
| 91 |
+
|
| 92 |
+
def write(self, buf):
|
| 93 |
+
temp_linebuf = self.linebuf + buf
|
| 94 |
+
self.linebuf = ""
|
| 95 |
+
for line in temp_linebuf.splitlines(True):
|
| 96 |
+
# From the io.TextIOWrapper docs:
|
| 97 |
+
# On output, if newline is None, any '\n' characters written
|
| 98 |
+
# are translated to the system default line separator.
|
| 99 |
+
# By default sys.stdout.write() expects '\n' newlines and then
|
| 100 |
+
# translates them so this is still cross platform.
|
| 101 |
+
if line[-1] == "\n":
|
| 102 |
+
encoded_message = line.encode("utf-8", "ignore").decode("utf-8")
|
| 103 |
+
self.logger.log(self.log_level, encoded_message.rstrip())
|
| 104 |
+
else:
|
| 105 |
+
self.linebuf += line
|
| 106 |
+
|
| 107 |
+
def flush(self):
|
| 108 |
+
if self.linebuf != "":
|
| 109 |
+
encoded_message = self.linebuf.encode("utf-8", "ignore").decode("utf-8")
|
| 110 |
+
self.logger.log(self.log_level, encoded_message.rstrip())
|
| 111 |
+
self.linebuf = ""
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def disable_torch_init():
|
| 115 |
+
"""
|
| 116 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
| 117 |
+
"""
|
| 118 |
+
import torch
|
| 119 |
+
|
| 120 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
| 121 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_gpu_memory(max_gpus=None):
|
| 125 |
+
"""Get available memory for each GPU."""
|
| 126 |
+
gpu_memory = []
|
| 127 |
+
num_gpus = (
|
| 128 |
+
torch.cuda.device_count()
|
| 129 |
+
if max_gpus is None
|
| 130 |
+
else min(max_gpus, torch.cuda.device_count())
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
for gpu_id in range(num_gpus):
|
| 134 |
+
with torch.cuda.device(gpu_id):
|
| 135 |
+
device = torch.cuda.current_device()
|
| 136 |
+
gpu_properties = torch.cuda.get_device_properties(device)
|
| 137 |
+
total_memory = gpu_properties.total_memory / (1024**3)
|
| 138 |
+
allocated_memory = torch.cuda.memory_allocated() / (1024**3)
|
| 139 |
+
available_memory = total_memory - allocated_memory
|
| 140 |
+
gpu_memory.append(available_memory)
|
| 141 |
+
return gpu_memory
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def violates_moderation(text):
|
| 145 |
+
"""
|
| 146 |
+
Check whether the text violates OpenAI moderation API.
|
| 147 |
+
"""
|
| 148 |
+
url = "https://api.openai.com/v1/moderations"
|
| 149 |
+
headers = {
|
| 150 |
+
"Content-Type": "application/json",
|
| 151 |
+
"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
|
| 152 |
+
}
|
| 153 |
+
text = text.replace("\n", "")
|
| 154 |
+
data = "{" + '"input": ' + f'"{text}"' + "}"
|
| 155 |
+
data = data.encode("utf-8")
|
| 156 |
+
try:
|
| 157 |
+
ret = requests.post(url, headers=headers, data=data, timeout=5)
|
| 158 |
+
flagged = ret.json()["results"][0]["flagged"]
|
| 159 |
+
except requests.exceptions.RequestException as e:
|
| 160 |
+
flagged = False
|
| 161 |
+
except KeyError as e:
|
| 162 |
+
flagged = False
|
| 163 |
+
|
| 164 |
+
return flagged
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def clean_flant5_ckpt(ckpt_path):
|
| 168 |
+
"""
|
| 169 |
+
Flan-t5 trained with HF+FSDP saves corrupted weights for shared embeddings,
|
| 170 |
+
Use this function to make sure it can be correctly loaded.
|
| 171 |
+
"""
|
| 172 |
+
index_file = os.path.join(ckpt_path, "pytorch_model.bin.index.json")
|
| 173 |
+
index_json = json.load(open(index_file, "r"))
|
| 174 |
+
|
| 175 |
+
weightmap = index_json["weight_map"]
|
| 176 |
+
|
| 177 |
+
share_weight_file = weightmap["shared.weight"]
|
| 178 |
+
share_weight = torch.load(os.path.join(ckpt_path, share_weight_file))[
|
| 179 |
+
"shared.weight"
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
for weight_name in ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]:
|
| 183 |
+
weight_file = weightmap[weight_name]
|
| 184 |
+
weight = torch.load(os.path.join(ckpt_path, weight_file))
|
| 185 |
+
weight[weight_name] = share_weight
|
| 186 |
+
torch.save(weight, os.path.join(ckpt_path, weight_file))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def pretty_print_semaphore(semaphore):
|
| 190 |
+
"""Print a semaphore in better format."""
|
| 191 |
+
if semaphore is None:
|
| 192 |
+
return "None"
|
| 193 |
+
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
"""A javascript function to get url parameters for the gradio web server."""
|
| 197 |
+
get_window_url_params_js = """
|
| 198 |
+
function() {
|
| 199 |
+
const params = new URLSearchParams(window.location.search);
|
| 200 |
+
url_params = Object.fromEntries(params);
|
| 201 |
+
console.log("url_params", url_params);
|
| 202 |
+
return url_params;
|
| 203 |
+
}
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def iter_over_async(
|
| 208 |
+
async_gen: AsyncGenerator, event_loop: AbstractEventLoop
|
| 209 |
+
) -> Generator:
|
| 210 |
+
"""
|
| 211 |
+
Convert async generator to sync generator
|
| 212 |
+
|
| 213 |
+
:param async_gen: the AsyncGenerator to convert
|
| 214 |
+
:param event_loop: the event loop to run on
|
| 215 |
+
:returns: Sync generator
|
| 216 |
+
"""
|
| 217 |
+
ait = async_gen.__aiter__()
|
| 218 |
+
|
| 219 |
+
async def get_next():
|
| 220 |
+
try:
|
| 221 |
+
obj = await ait.__anext__()
|
| 222 |
+
return False, obj
|
| 223 |
+
except StopAsyncIteration:
|
| 224 |
+
return True, None
|
| 225 |
+
|
| 226 |
+
while True:
|
| 227 |
+
done, obj = event_loop.run_until_complete(get_next())
|
| 228 |
+
if done:
|
| 229 |
+
break
|
| 230 |
+
yield obj
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def detect_language(text: str) -> str:
|
| 234 |
+
"""Detect the langauge of a string."""
|
| 235 |
+
import polyglot # pip3 install polyglot pyicu pycld2
|
| 236 |
+
from polyglot.detect import Detector
|
| 237 |
+
from polyglot.detect.base import logger as polyglot_logger
|
| 238 |
+
import pycld2
|
| 239 |
+
|
| 240 |
+
polyglot_logger.setLevel("ERROR")
|
| 241 |
+
|
| 242 |
+
try:
|
| 243 |
+
lang_code = Detector(text).language.name
|
| 244 |
+
except (pycld2.error, polyglot.detect.base.UnknownLanguage):
|
| 245 |
+
lang_code = "unknown"
|
| 246 |
+
return lang_code
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def parse_gradio_auth_creds(filename):
|
| 250 |
+
"""Parse a username:password file for gradio authorization."""
|
| 251 |
+
gradio_auth_creds = []
|
| 252 |
+
with open(filename, "r", encoding="utf8") as file:
|
| 253 |
+
for line in file.readlines():
|
| 254 |
+
gradio_auth_creds += [x.strip() for x in line.split(",") if x.strip()]
|
| 255 |
+
if gradio_auth_creds:
|
| 256 |
+
auth = [tuple(cred.split(":")) for cred in gradio_auth_creds]
|
| 257 |
+
else:
|
| 258 |
+
auth = None
|
| 259 |
+
return auth
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def is_partial_stop(output, stop_str):
|
| 263 |
+
"""Check whether the output contains a partial stop str."""
|
| 264 |
+
for i in range(0, min(len(output), len(stop_str))):
|
| 265 |
+
if stop_str.startswith(output[-i:]):
|
| 266 |
+
return True
|
| 267 |
+
return False
|