forked from ucbepic/docetl
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
126 additions
and
185 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,106 +1,60 @@ | ||
from typing import Any, Dict, List, Optional, Tuple | ||
from pydantic import BaseModel | ||
from pydantic import BaseModel, create_model | ||
from docetl.operations.base import BaseOperation | ||
from outlines import generate, models | ||
from transformers import AutoModelForCausalLM, AutoTokenizer | ||
import json | ||
|
||
class HuggingFaceMapOperation(BaseOperation): | ||
class schema(BaseOperation.schema): | ||
name: str | ||
type: str = "hf_map" | ||
model_path: str | ||
use_local_model: bool = False | ||
device: str = "cuda" | ||
output_schema: Dict[str, Any] | ||
prompt_template: str | ||
batch_size: Optional[int] = 10 | ||
max_tokens: int = 4096 | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
def __init__(self, config: Dict[str, Any], runner=None, *args, **kwargs): | ||
super().__init__( | ||
config=config, | ||
default_model=config.get('default_model', config['model_path']), | ||
max_threads=config.get('max_threads', 1), | ||
runner=runner | ||
) | ||
|
||
self.model = models.transformers( | ||
self.config["model_path"] | ||
) | ||
|
||
# Create a dynamic Pydantic model from the output schema | ||
field_definitions = { | ||
k: (eval(v) if isinstance(v, str) else v, ...) | ||
for k, v in self.config["output_schema"].items() | ||
} | ||
output_model = create_model('OutputModel', **field_definitions) | ||
|
||
if self.config["use_local_model"]: | ||
llm = AutoModelForCausalLM.from_pretrained( | ||
self.config["model_path"], | ||
device_map=self.config["device"] | ||
) | ||
tokenizer = AutoTokenizer.from_pretrained(self.config["model_path"]) | ||
self.model = models.Transformers(llm, tokenizer) | ||
self.tokenizer = tokenizer | ||
else: | ||
self.model = models.transformers( | ||
self.config["model_path"], | ||
device=self.config["device"] | ||
) | ||
self.tokenizer = self.model.tokenizer | ||
|
||
output_model = BaseModel.model_validate(self.config["output_schema"]) | ||
self.processor = generate.json( | ||
self.model, | ||
output_model, | ||
max_tokens=self.config["max_tokens"] | ||
output_model | ||
) | ||
|
||
def syntax_check(self) -> None: | ||
"""Validate the operation configuration.""" | ||
config = self.schema(**self.config) | ||
|
||
if not config.model_path: | ||
raise ValueError("model_path is required") | ||
|
||
if not config.output_schema: | ||
raise ValueError("output_schema is required") | ||
|
||
if not config.prompt_template: | ||
raise ValueError("prompt_template is required") | ||
|
||
def create_prompt(self, item: Dict[str, Any]) -> str: | ||
"""Create a prompt from the template and input data.""" | ||
messages = [ | ||
{ | ||
'role': 'user', | ||
'content': self.config["prompt_template"] | ||
}, | ||
{ | ||
'role': 'assistant', | ||
'content': "I understand and will process the input as requested." | ||
}, | ||
{ | ||
'role': 'user', | ||
'content': str(item) | ||
} | ||
] | ||
return self.tokenizer.apply_chat_template( | ||
messages, | ||
tokenize=False | ||
) | ||
self.schema(**self.config) | ||
|
||
def process_item(self, item: Dict[str, Any]) -> Dict[str, Any]: | ||
"""Process a single item through the model.""" | ||
prompt = self.create_prompt(item) | ||
try: | ||
result = self.processor(prompt) | ||
result = self.processor(self.config["prompt_template"] + "\n" + str(item)) | ||
result_dict = result.model_dump() | ||
final_dict = {**item, **result_dict} | ||
return json.loads(json.dumps(final_dict, indent=2)) | ||
return final_dict | ||
except Exception as e: | ||
self.console.print(f"Error processing item: {e}") | ||
return json.loads(json.dumps(item, indent=2)) | ||
return item | ||
|
||
def execute(self, input_data: List[Dict]) -> Tuple[List[Dict], float]: | ||
@classmethod | ||
def execute(cls, config: Dict[str, Any], input_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], float]: | ||
"""Execute the operation on the input data.""" | ||
if self.status: | ||
self.status.stop() | ||
|
||
results = [] | ||
batch_size = self.config.get("batch_size", 10) | ||
|
||
for i in range(0, len(input_data), batch_size): | ||
batch = input_data[i:i + batch_size] | ||
batch_results = [self.process_item(item) for item in batch] | ||
results.extend(batch_results) | ||
|
||
if self.status: | ||
self.status.start() | ||
|
||
instance = cls(config) | ||
results = [instance.process_item(item) for item in input_data] | ||
return results, 0.0 |
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