-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
open source model support #65
Open
Mac0q
wants to merge
1
commit into
microsoft:vyokky/dev
Choose a base branch
from
Mac0q:dev_
base: vyokky/dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+764
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
#Method to generate response from prompt and image using the Llava model | ||
@torch.inference_mode() | ||
def direct_generate_llava(self, params): | ||
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor | ||
|
||
prompt = params["prompt"] | ||
image = params.get("image", None) | ||
if image is not None: | ||
if DEFAULT_IMAGE_TOKEN not in prompt: | ||
raise ValueError("Number of image does not match number of <image> tokens in prompt") | ||
|
||
image = load_image_from_base64(image) | ||
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] | ||
image = image.to(self.model.device, dtype=self.model.dtype) | ||
images = image.unsqueeze(0) | ||
|
||
replace_token = DEFAULT_IMAGE_TOKEN | ||
if getattr(self.model.config, 'mm_use_im_start_end', False): | ||
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN | ||
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token) | ||
|
||
num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches | ||
else: | ||
return {"text": "No image provided", "error_code": 0} | ||
|
||
temperature = float(params.get("temperature", 1.0)) | ||
top_p = float(params.get("top_p", 1.0)) | ||
max_context_length = getattr(model.config, 'max_position_embeddings', 2048) | ||
max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024) | ||
stop_str = params.get("stop", None) | ||
do_sample = True if temperature > 0.001 else False | ||
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) | ||
keywords = [stop_str] | ||
max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens) | ||
|
||
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) | ||
|
||
input_seq_len = input_ids.shape[1] | ||
|
||
generation_output = self.model.generate( | ||
inputs=input_ids, | ||
do_sample=do_sample, | ||
temperature=temperature, | ||
top_p=top_p, | ||
max_new_tokens=max_new_tokens, | ||
images=images, | ||
use_cache=True, | ||
) | ||
|
||
generation_output = generation_output[0, input_seq_len:] | ||
decoded = tokenizer.decode(generation_output, skip_special_tokens=True) | ||
|
||
response = {"text": decoded} | ||
print("response", response) | ||
return response | ||
|
||
|
||
# The API is included in llava and cogagent installations. If you customize your model, you can install fastapi via pip or uncomment the library in the requirements. | ||
# import FastAPI | ||
# app = FastAPI() | ||
|
||
#For llava | ||
@app.post("/chat/completions") | ||
async def generate_llava(request: Request): | ||
params = await request.json() | ||
response_data = worker.direct_generate_llava(params) | ||
return response_data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import time | ||
from typing import Any, Optional | ||
|
||
import requests | ||
|
||
from ufo.utils import print_with_color | ||
from .base import BaseService | ||
|
||
|
||
class CogAgentService(BaseService): | ||
def __init__(self, config, agent_type: str): | ||
self.config_llm = config[agent_type] | ||
self.config = config | ||
self.max_retry = self.config["MAX_RETRY"] | ||
self.timeout = self.config["TIMEOUT"] | ||
self.max_tokens = 2048 #default max tokens for cogagent for now | ||
|
||
def chat_completion( | ||
self, | ||
messages, | ||
n, | ||
temperature: Optional[float] = None, | ||
max_tokens: Optional[int] = None, | ||
top_p: Optional[float] = None, | ||
**kwargs: Any, | ||
): | ||
""" | ||
Generate chat completions based on given messages. | ||
Args: | ||
messages (list): A list of messages. | ||
n (int): The number of completions to generate. | ||
temperature (float, optional): The temperature for sampling. Defaults to None. | ||
max_tokens (int, optional): The maximum number of tokens in the completion. Defaults to None. | ||
top_p (float, optional): The cumulative probability for top-p sampling. Defaults to None. | ||
**kwargs: Additional keyword arguments. | ||
Returns: | ||
tuple: A tuple containing the generated texts and None. | ||
""" | ||
|
||
temperature = temperature if temperature is not None else self.config["TEMPERATURE"] | ||
max_tokens = max_tokens if max_tokens is not None else self.config["MAX_TOKENS"] | ||
top_p = top_p if top_p is not None else self.config["TOP_P"] | ||
|
||
texts = [] | ||
for i in range(n): | ||
image_base64 = None | ||
if self.config_llm["VISUAL_MODE"]: | ||
image_base64 = messages[1]['content'][-2]['image_url']\ | ||
['url'].split('base64,')[1] | ||
prompt = messages[0]['content'] + messages[1]['content'][-1]['text'] | ||
|
||
payload = { | ||
'model': self.config_llm['API_MODEL'], | ||
'prompt': prompt, | ||
'temperature': temperature, | ||
'top_p': top_p, | ||
'max_new_tokens': self.max_tokens, | ||
"image":image_base64 | ||
} | ||
|
||
for _ in range(self.max_retry): | ||
try: | ||
response = requests.post(self.config_llm['API_BASE']+"/chat/completions", json=payload) | ||
if response.status_code == 200: | ||
response = response.json() | ||
text = response["text"] | ||
texts.append(text) | ||
break | ||
else: | ||
raise Exception( | ||
f"Failed to get completion with error code {response.status_code}: {response.text}", | ||
) | ||
except Exception as e: | ||
print_with_color(f"Error making API request: {e}", "red") | ||
try: | ||
print_with_color(response, "red") | ||
except: | ||
_ | ||
time.sleep(3) | ||
continue | ||
return texts, None |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
from the previous version, it should be 10.3.0.