72 lines
2.5 KiB
Python
72 lines
2.5 KiB
Python
from typing import NamedTuple
|
|
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, TextStreamer
|
|
import torch
|
|
|
|
class InferenceResult(NamedTuple):
|
|
reasoning: str
|
|
actions: str
|
|
|
|
class LlmEngine:
|
|
def __init__(self, model_path: str):
|
|
"""
|
|
Initialize the LLM Engine with a model path.
|
|
|
|
Args:
|
|
model_path: Path to the model weights to be used.
|
|
"""
|
|
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
self.torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
|
print(f"device: {self.device}")
|
|
self.set_model_path(model_path)
|
|
|
|
def set_model_path(self, model_path: str):
|
|
"""
|
|
Load the model from the specified path.
|
|
|
|
Args:
|
|
model_path: Path to the model weights to load.
|
|
"""
|
|
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
|
model = AutoModelForCausalLM.from_pretrained(
|
|
model_path,
|
|
return_dict=True,
|
|
low_cpu_mem_usage=True,
|
|
torch_dtype=self.torch_dtype,
|
|
device_map="auto",
|
|
trust_remote_code=True,
|
|
).to(self.device)
|
|
if tokenizer.pad_token_id is None:
|
|
tokenizer.pad_token_id = tokenizer.eos_token_id
|
|
if model.config.pad_token_id is None:
|
|
model.config.pad_token_id = model.config.eos_token_id
|
|
self.pipeline = pipeline(
|
|
"text-generation",
|
|
model=model,
|
|
tokenizer=tokenizer,
|
|
torch_dtype=torch.float16,
|
|
device_map="auto",
|
|
)
|
|
|
|
def infer(self, system_prompt: str, main_context: str, action_schema: str) -> InferenceResult:
|
|
"""
|
|
Run inference using the system prompt and main context, while validating actions against the provided XML schema.
|
|
|
|
Args:
|
|
system_prompt: The system prompt string
|
|
main_context: The main context string after templating
|
|
action_schema: XML schema to validate the generated actions
|
|
|
|
Returns:
|
|
InferenceResult: the actions validate against the schema
|
|
"""
|
|
pass
|
|
|
|
def finetune(self, dataset_paths: list, output_dir: str):
|
|
"""
|
|
Fine-tune the model with new datasets and save the updated model weights.
|
|
|
|
Args:
|
|
dataset_paths: List of paths to datasets for fine-tuning.
|
|
output_dir: Directory where the updated model weights will be saved.
|
|
"""
|
|
pass |