Instructions to use microsoft/Florence-2-base-ft with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use microsoft/Florence-2-base-ft with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="microsoft/Florence-2-base-ft", trust_remote_code=True)# Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("microsoft/Florence-2-base-ft", trust_remote_code=True) model = AutoModelForMultimodalLM.from_pretrained("microsoft/Florence-2-base-ft", trust_remote_code=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use microsoft/Florence-2-base-ft with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "microsoft/Florence-2-base-ft" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Florence-2-base-ft", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/microsoft/Florence-2-base-ft
- SGLang
How to use microsoft/Florence-2-base-ft with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "microsoft/Florence-2-base-ft" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Florence-2-base-ft", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "microsoft/Florence-2-base-ft" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Florence-2-base-ft", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use microsoft/Florence-2-base-ft with Docker Model Runner:
docker model run hf.co/microsoft/Florence-2-base-ft
Unable to load fine tuned model from local directory
Unable to load fine tuned model from local directory
Hello, I'm trying to finetune the florence-2-base-ft model from huggingface, for that, I use the following train function and save my finetuned model with the .save_pretrained() method. Then, I would like to load this finetuned model with .from_pretrained() method. However, I got an error message.
Steps to reproduce
Here is the train_model() function that I use for finetuning the florence-2-base-ft model.
def train_model(train_loader, val_loader, model, processor, device, epochs=10, lr=1e-6):
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
num_training_steps = epochs * len(train_loader)
lr_scheduler = get_scheduler(
name="linear",
optimizer=optimizer,
num_warmup_steps=0,
num_training_steps=num_training_steps,
)
for epoch in range(epochs):
model.train()
train_loss = 0
i = -1
for batch in tqdm(train_loader, desc=f"Training Epoch {epoch + 1}/{epochs}"):
i += 1
inputs, answers = batch
input_ids = inputs["input_ids"]
pixel_values = inputs["pixel_values"]
labels = processor.tokenizer(text=answers, return_tensors="pt", padding=True, return_token_type_ids=False).input_ids.to(device)
outputs = model(input_ids=input_ids, pixel_values=pixel_values, labels=labels)
loss = outputs.loss
loss.backward()
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
train_loss += loss.item()
avg_train_loss = train_loss / len(train_loader)
print(f"Average Training Loss: {avg_train_loss}")
# Validation phase
model.eval()
val_loss = 0
with torch.no_grad():
for batch in tqdm(val_loader, desc=f"Validation Epoch {epoch + 1}/{epochs}"):
inputs, answers = batch
input_ids = inputs["input_ids"]
pixel_values = inputs["pixel_values"]
labels = processor.tokenizer(text=answers, return_tensors="pt", padding=True, return_token_type_ids=False).input_ids.to(device)
outputs = model(input_ids=input_ids, pixel_values=pixel_values, labels=labels)
loss = outputs.loss
val_loss += loss.item()
avg_val_loss = val_loss / len(val_loader)
print(f"Average Validation Loss: {avg_val_loss}")
# Save model checkpoint
output_dir = f"./model_checkpoints/epoch_{epoch+1}"
os.makedirs(output_dir, exist_ok=True)
model.save_pretrained(output_dir)
processor.save_pretrained(output_dir)
return model, processor
Then, to load my finetuned model, I do it like that :
model_finetuned = AutoModelForCausalLM.from_pretrained("./model_checkpoints/epoch_2", trust_remote_code=True)
Stacktrace
How can I solve this?
Did I do something wrong to save/load my model, or is it due to the fact that florence-2 was released recently?
Thanks in advance!
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
config.vision_config.model_type = "davit"
model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True,
config=config,
).to(device)
processor = AutoProcessor.from_pretrained(
model_id, trust_remote_code=True, config=config
)
Change config when load model, maybe it can solve your problem.
It works ! thank you !
On using the processor using: processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True, config=config), leads to the following error when loading:
" Can't instantiate a processor, a tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains the files of at least one of those processing classes."
And the folder which is reading the files are made with self.model.save_pretrained(f"./models/microsoft/Florence-2-base") and it contains: config.json, generation_config.json, and a model.safetensors
Any help?
Hello, do you have a processor_config.json or a preprocessor_config.json file ? If that's not the case, maybe you forgot to save the processor:
model.save_pretrained(output_dir)
processor.save_pretrained(output_dir)
