The github for llama inference:
Name Last commit message Last commit date
parent directory
..
chat_completion
Fix quantization for inference
4 months ago
README.md
Fixed readme with renaming file name
4 days ago
inference.py
Make gradio and langchain optional dependencies (#676)
2 months ago
multi_modal_infer.py
convertion missing preprocessor_config.json.
2 weeks ago
multi_modal_infer_gradio_UI.py
Renamed the file and made that G small of gradio
4 days ago
samsum_prompt.txt
recipes/quickstart folder updated
5 months ago
README.md
Local Inference
Hugging face setup
Important Note: Before running the inference, you'll need your Hugging Face access token, which you can get at your Settings page here. Then run huggingface-cli login and copy and paste your Hugging Face access token to complete the login to make sure the scripts can download Hugging Face models if needed.
Multimodal Inference
For Multi-Modal inference we have added multi_modal_infer.py which uses the transformers library.
The way to run this would be:
python multi_modal_infer.py --image_path PATH_TO_IMAGE --prompt_text "Describe this image" --temperature 0.5 --top_p 0.8 --model_name "meta-llama/Llama-3.2-11B-Vision-Instruct"
Multi-modal Inferencing Using gradio UI for inferencing
For multi-modal inferencing using gradio UI we have added multi_modal_infer_gradio_UI.py which used gradio and transformers library.
Steps to Run
The way to run this would be:
Ensure having proper access to llama 3.2 vision models, then run the command given below
python multi_modal_infer_gradio_UI.py --hf_token
Text-only Inference
For local inference we have provided an inference script. Depending on the type of finetuning performed during training the inference script takes different arguments.
To finetune all model parameters the output dir of the training has to be given as --model_name argument. In the case of a parameter efficient method like lora the base model has to be given as --model_name and the output dir of the training has to be given as --peft_model argument. Additionally, a prompt for the model in the form of a text file has to be provided. The prompt file can either be piped through standard input or given as --prompt_file parameter.
Content Safety The inference script also supports safety checks for both user prompt and model outputs. In particular, we use two packages, AuditNLG and Azure content safety.
Note If using Azure content Safety, please make sure to get the endpoint and API key as described here and add them as the following environment variables,CONTENT_SAFETY_ENDPOINT and CONTENT_SAFETY_KEY.
python inference.py --model_name <training_config.output_dir> --prompt_file <test_prompt_file> --use_auditnlg
The folder contains test prompts for summarization use-case:
samsum_prompt.txt
...
Note on Llama version < 3.1 The default padding token in HuggingFace Tokenizer is None. To use padding the padding token needs to be added as a special token to the tokenizer, which in this case requires to resize the token_embeddings as shown below:
tokenizer.add_special_tokens(
{
code
"pad_token": "<PAD>",
}
)
model.resize_token_embeddings(model.config.vocab_size + 1)
Padding would be required for batched inference. In this example, batch size = 1 so essentially padding is not required. However, we added the code pointer as an example in case of batch inference. For Llama version 3.1 use the special token <|finetune_right_pad_id|> (128004) for padding.
Chat completion
The inference folder also includes a chat completion example, that adds built-in safety features in fine-tuned models to the prompt tokens. To run the example:
python chat_completion/chat_completion.py --model_name "PATH/TO/MODEL/7B/" --prompt_file chat_completion/chats.json --quantization 8bit --use_auditnlg
Flash Attention and Xformer Memory Efficient Kernels
Setting use_fast_kernels will enable using of Flash Attention or Xformer memory-efficient kernels based on the hardware being used. This would speed up inference when used for batched inputs. This has been enabled in optimum library from HuggingFace as a one-liner API, please read more here.
python inference.py --model_name <training_config.output_dir> --peft_model <training_config.output_dir> --prompt_file <test_prompt_file> --use_auditnlg --use_fast_kernels
Inference with FSDP checkpoints
In case you have fine-tuned your model with pure FSDP and saved the checkpoints with "SHARDED_STATE_DICT" as shown here, you can use this converter script to convert the FSDP Sharded checkpoints into HuggingFace checkpoints. This enables you to use the inference script normally as mentioned above. To convert the checkpoint use the following command:
This is helpful if you have fine-tuned you model using FSDP only as follows:
torchrun --nnodes 1 --nproc_per_node 8 recipes/quickstart/finetuning/finetuning.py --enable_fsdp --model_name /path_of_model_folder/7B --dist_checkpoint_root_folder model_checkpoints --dist_checkpoint_folder fine-tuned --fsdp_config.pure_bf16
Then convert your FSDP checkpoint to HuggingFace checkpoints using:
--HF_model_path_or_name specifies the HF Llama model name or path where it has config.json and tokenizer.json
By default, training parameter are saved in train_params.yaml in the path where FSDP checkpoints are saved, in the converter script we frist try to find the HugingFace model name used in the fine-tuning to load the model with configs from there, if not found user need to provide it.
How to use them in google colab?
Write the full code.
Assistant
To use the Llama inference scripts in Google Colab, you'll need to follow several steps to set up your environment, download the necessary libraries and models, and execute the inference scripts. I'll provide you with a complete setup guide alongside the code snippets needed to run the inference in Google Colab. Here’s how you can get started:
Step 1: Environment Setup
Import necessary libraries: You'll need to install libraries such as transformers, torch, gradio, and potentially others used in the scripts.
Log in to Hugging Face: Use your Hugging Face access token to download models.
python
from huggingface_hub import notebook_login
notebook_login()
You'll be prompted to paste your Hugging Face access token here.
Step 2: Prepare Models and Scripts
Cloning the Repository: If the scripts you want to use are hosted on GitHub, you can clone the repository to load the scripts into your Colab environment.
So I run step 3:
code: !python inference.py --model_name <training_config.output_dir> --prompt_file <test_prompt_file> --use_auditnlg
output: /bin/bash: line 1: training_config.output_dir: No such file or directory
Assistant
The error you're seeing suggests that the <training_config.output_dir> placeholder was not replaced with the actual directory path where your model is saved. In Python scripts and command-line commands, placeholders like these need to be substituted with real values. Here’s how you can handle this:
Steps to Resolve the Issue
Identify the Correct Model Path:
You need to replace <training_config.output_dir> with the actual path to the directory where your trained model is stored. This path should point to the folder containing the model's configuration files, weights, etc.
Specify the Prompt File:
Similarly, replace <test_prompt_file> with the path to the text file containing your prompts for inference.
Example Command:
If your model directory is models/my_trained_model and your prompt file is prompts/test_prompt.txt, you should run the command like this:
Ensure that your trained model and prompt files are uploaded to your Colab environment or accessible via specified paths.
You can use the file browser in Colab to see and upload files:
python
from google.colab import files
# To upload model directory and test prompt files directly
uploaded = files.upload()
Update and Run Your Command:
Substitute the example paths with your actual file paths in the command.
Verify Model and Prompt File:
If you are unsure about the directory structure, run the following commands to inspect files:
bash
!ls models/my_trained_model
!ls prompts/
Summary:
Ensure that each placeholder in your command is replaced with the correct path to your model directory and prompt file, thus enabling the script to access and process the necessary data. This involves knowing where your outputs from training are stored and which files need to be loaded for inference.
User
I don't have prompt file
Assistant
If you don't have a prompt file and you'd like to generate input directly from within your script or Google Colab environment, you can modify the inference process to take input from a string or a command-line argument instead of a file. Here's how you can handle that scenario:
Option 1: Direct Prompt Input via Command Line
You can directly pass the prompt as a string by modifying the inference script or how you run it. If the script allows for standard input or if you can edit the script, you can provide input in these ways:
Modify the Script to Accept Direct Input:
If the script allows for standard input, you can pipe the prompt:
Modify the inference.py script to accept a command-line argument for prompt text and modify the script to use that input if the prompt file is not specified.
Example snippet in inference.py (pseudo-code):
python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--prompt_file', type=str, default=None)
parser.add_argument('--prompt_text', type=str, default="")
args = parser.parse_args()
if args.prompt_file:
with open(args.prompt_file, 'r') as file:
prompt = file.read()
else:
prompt = args.prompt_text
# Continue with processing `prompt` as needed
Option 2: Generate Input from Within a Jupyter Cell
If you're using a Jupyter environment like Google Colab:
python
User
Ok, so the ouptut is
CompletedProcess(args='python inference.py --model_name /content/drive/MyDrive/model/Converted_HF_Model --prompt_text "You are a helpful chatbot." --use_auditnlg', returncode=1)
Is it normal?
Assistant
A CompletedProcess object with a returncode of 1 typically indicates that the script did not execute successfully. This return code usually means there was an error during the execution of the script. Here's how you can diagnose and potentially resolve the issue:
Steps to Diagnose the Error
Check the Error Message:
Capturing standard error output can help identify the problem. Modify the subprocess.run call to capture and print the error output:
python
import subprocess
model_name = '/content/drive/MyDrive/model/Converted_HF_Model'
prompt_text = 'You are a helpful chatbot.'
result = subprocess.run(
f'python inference.py --model_name {model_name} --prompt_text "{prompt_text}" --use_auditnlg',
shell=True,
capture_output=True,
text=True
)
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)
Look for Common Issues:
File Not Found: Ensure inference.py and your model path are correct and accessible in your current working directory.
Library Issues: Ensure all necessary Python packages (such as torch, transformers, and any other dependencies) are installed.
Script Errors: Look for errors in inference.py that may not handle the provided arguments correctly or require additional dependencies.
Inspect the Error Output:
The printed STDERR output from the terminal will provide specific error messages that can help pinpoint the issue. Look for file paths that could be wrong, missing packages, or misconfigured environment variables.
Permissions and Data Access:
Verify that your script has the necessary permissions to access files and directories, especially if your files are on Google Drive.
Library Versioning:
Sometimes compatibility issues with specific versions of libraries might cause errors. Ensure you have compatible versions of transformers, torch, and other relevant libraries.
General Troubleshooting Tips
Check paths thoroughly: Make sure all file paths are absolute paths in Colab for directories and dependencies.
Update Environment: Refresh your library installs:
python
!pip install --upgrade transformers torch
By following these steps, you should be able to identify what specifically is causing the returncode of 1 and address it accordingly. If you find a specific error message, that will guide what needs to be adjusted in your code or environment.
User
STDOUT:
STDERR: Traceback (most recent call last):
File "/content/llama-recipes/recipes/quickstart/inference/local_inference/inference.py", line 13, in
from llama_recipes.inference.model_utils import load_model, load_peft_model
ModuleNotFoundError: No module named 'llama_recipes'
Assistant
The error ModuleNotFoundError: No module named 'llama_recipes' indicates that the script is attempting to import a module that is not available in your current environment. Here's how you can resolve this issue in your Google Colab environment:
Steps to Fix the Error
Ensure Correct Path Setup:
If you have cloned a repository that contains llama_recipes, you should verify the directory structure and ensure your Python environment recognizes the module.
If the llama_recipes is in a directory you've cloned, make sure you're in the correct working directory in Colab:
python
import os
os.chdir('/content/llama-recipes') # Change to the directory where the module exists
Install as a Python Package (if applicable):
If llama_recipes should be installed as a package, and comes with a setup.py, you can install it using:
python
!pip install -e .
Make sure you're in the correct directory where the setup.py file is located when running this command.
Check PYTHONPATH:
Sometimes, it may be necessary to add the directory containing llama_recipes to your PYTHONPATH so Python knows where to find the module:
python
import sys
sys.path.append('/content/llama-recipes') # Add the path to your module
Verify Directory Structure:
Ensure that the directory structure reflects Python package requirements. If llama_recipes is structured as a package, it should have an __init__.py file in that directory.
Re-run the Script:
After these setup steps, try running your inference script again:
Re-clone the Repository: If the directory structure is unclear, consider re-cloning the repository and checking for any missing or misnamed files.
Check Dependencies: Ensure that all dependencies and imported modules within llama_recipes are also satisfied and available in your Colab environment.
After ensuring the correct path setup and module availability, the import error should be resolved, allowing your inference script to execute correctly.
User
What happen?
STDOUT:
STDERR: python3: can't open file '/content/llama-recipes/inference.py': [Errno 2] No such file or directory
Assistant
The error message can't open file '/content/llama-recipes/inference.py': [Errno 2] No such file or directory indicates that the specified file path does not exist in your directory. This discrepancy often occurs due to an incorrect file path or a directory structure mismatch. Here’s how you can resolve this issue:
Steps to Resolve the File Not Found Error:
Verify Directory Structure:
Ensure that the directory structure matches the path you're providing in your command. Use the following command to list your directories and locate where inference.py is situated:
python
!ls /content/llama-recipes # Adjust the path as necessary
Change Directory:
Navigate to the correct directory where inference.py is located, then run the script. If inference.py is in a subdirectory, adjust your path to include it:
python
import os
os.chdir('/content/your-correct-path') # Set the working directory to where inference.py resides
Correct the Command Path:
Make sure your command points to the correct location of inference.py. Once the working directory is set appropriately, run:
python
model_name = '/content/drive/MyDrive/model/Converted_HF_Model'
prompt_text = 'You are a helpful chatbot.'
result = subprocess.run(
f'python path/to/inference.py --model_name {model_name} --prompt_text "{prompt_text}" --use_auditnlg',
shell=True,
capture_output=True,
text=True
)
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)
Ensure Cloning of the Repository:
If this is a cloned repository, ensure that it's cloned in the location you expect:
You can also use the full path to inference.py while running it, especially when storing scripts and data in separate directories.
Re-check File Locations:
Double-check Google Drive locations if they are involved. Sometimes paths referenced from Google Drive require mounting:
By following these steps, you should be able to pinpoint the correct location of inference.py and properly execute your script from the command line. Double-checking path correctness is crucial to running scripts without encountering file not found errors in environments like Google Colab.
User
STDOUT:
STDERR: Traceback (most recent call last):
File "/content/llama-recipes/recipes/quickstart/inference/local_inference/inference.py", line 13, in
from llama_recipes.inference.model_utils import load_model, load_peft_model
ModuleNotFoundError: No module named 'llama_recipes'
Assistant
The error ModuleNotFoundError: No module named 'llama_recipes' suggests that Python is unable to locate the llama_recipes module, even though it's supposed to be part of your directory structure. This issue commonly arises from misconceptions about the directory hierarchy or the need to set the PYTHONPATH. Here’s how to troubleshoot and fix this problem:
Steps to Resolve the Module Import Error
Check Directory Structure:
Verify that your project directory has the following structure, assuming llama_recipes is supposed to be a package:
Check the presence of an __init__.py file inside the llama_recipes directory. This file makes Python treat the directory as a package.
Add to PYTHONPATH:
Explicitly add the directory containing llama_recipes to the Python search path. This will ensure Python recognizes it as a package:
python
import sys
sys.path.append('/content/llama-recipes') # Add the directory containing the package
Add this at the top of your script if you have access, otherwise include it in your Colab notebook before importing or running scripts.
Change the Current Working Directory:
Before running your command, ensure you are in the right directory:
python
import os
os.chdir('/content/llama-recipes/recipes/quickstart/inference/local_inference')
Use Explicit Module Execution:
Run your script using module syntax if all else fails, but ensure paths are provided correctly:
User
STDERR: /usr/bin/python3: Error while finding module specification for 'llama_recipes.recipes.quickstart.inference.local_inference.inference' (ModuleNotFoundError: No module named 'llama_recipes.recipes')
Assistant
The error indicates that Python is attempting to locate a module using a dotted path but can't find it, suggesting a problem with how the packages and modules are organized or the setup of the Python environment. Here's how you can address this issue:
Steps to Resolve the ModuleNotFoundError
Verify Directory Structure:
Ensure that the directory structure where your script or package lives mirrors the namespace hierarchy you're trying to access. For instance:
Each folder that's part of the package hierarchy should ideally contain an __init__.py file, indicating to Python that this directory is a package. Though Python 3.3+ doesn't strictly require these, they're useful for ensuring compatibility and controlling imports.
Adjust PYTHONPATH:
Add the parent directory of llama_recipes to PYTHONPATH so Python can successfully navigate the package structure:
python
import sys
sys.path.append('/content/llama-recipes') # Adjust path to where `llama_recipes` resides
Make sure this is done before any imports that rely on this path.
Change to Correct Working Directory:
When executing a script via a module path, ensure you are in the base directory of your package:
python
import os
os.chdir('/content/llama-recipes') # Set to top-level directory containing the package
Run with Module Syntax:
Instead of referring to the script directly, run your script using the module syntax if correctly structured:
bash
User
The code of inference.py:
Copyright (c) Meta Platforms, Inc. and affiliates.
This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
import os
import sys
import time
import fire
import torch
from accelerate.utils import is_xpu_available
from llama_recipes.inference.model_utils import load_model, load_peft_model
from llama_recipes.inference.safety_utils import AgentType, get_safety_checker
from transformers import AutoTokenizer
def main(
model_name,
peft_model: str = None,
quantization: str = None, # Options: 4bit, 8bit
max_new_tokens=100, # The maximum numbers of tokens to generate
prompt_file: str = None,
seed: int = 42, # seed value for reproducibility
do_sample: bool = True, # Whether or not to use sampling ; use greedy decoding otherwise.
min_length: int = None, # The minimum length of the sequence to be generated, input prompt + min_new_tokens
use_cache: bool = True, # [optional] Whether or not the model should use the past last key/values attentions Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
top_p: float = 1.0, # [optional] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
temperature: float = 1.0, # [optional] The value used to modulate the next token probabilities.
top_k: int = 50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
repetition_penalty: float = 1.0, # The parameter for repetition penalty. 1.0 means no penalty.
length_penalty: int = 1, # [optional] Exponential penalty to the length that is used with beam-based generation.
enable_azure_content_safety: bool = False, # Enable safety check with Azure content safety api
enable_sensitive_topics: bool = False, # Enable check for sensitive topics using AuditNLG APIs
enable_salesforce_content_safety: bool = True, # Enable safety check with Salesforce safety flan t5
enable_llamaguard_content_safety: bool = False,
max_padding_length: int = None, # the max padding length to be used with tokenizer padding the prompts.
use_fast_kernels: bool = False, # Enable using SDPA from PyTroch Accelerated Transformers, make use Flash Attention and Xformer memory-efficient kernels
share_gradio: bool = False, # Enable endpoint creation for gradio.live
**kwargs,
):
# Set the seeds for reproducibility
if is_xpu_available():
torch.xpu.manual_seed(seed)
else:
torch.cuda.manual_seed(seed)
torch.manual_seed(seed)
code
Assistant
Given the inference.py script you've shared, there are a few key things to note regarding the ModuleNotFoundError. Here’s how to make sure the script can successfully find and import the llama_recipes module:
Steps to Resolve Import Issues
Ensure the Directory Structure is Correct
Check that the directory structure aligns with the import statements. If the model_utils and safety_utils are supposed to be under a directory named llama_recipes/inference/, the directory structure should be:
Ensure your script can locate the llama_recipes package by adding its parent directory to the Python path, or by adjusting the current working directory to the root directory before running the script:
python
import sys
import os
# Assuming llama_recipes folder is directly under /content
sys.path.append('/content/llama-recipes')
os.chdir('/content/llama-recipes/recipes/quickstart/inference/local_inference')
Run with Python Module Syntax (As Needed)
If you organized your code such that the Python path needs to be explicit about module names (using __main__), make sure that llama_recipes indeed reflects the Python package path:
Double-check all directory names and ensure all necessary files, especially __init__.py, are present in their respective directories to define a package.
Once the inferences are complete, clear any outputs and optionally remove files as per requirement. This process helps manage your session's disk space usage.
Note:
Ensure paths and model settings match your specific setup.
Some parameters (e.g., model_name, prompt_file, and Hugging Face paths) must be adapted to fit your environment and specific use case.
If additional libraries or credentials are needed, ensure they’re set up accordingly before starting the inference process.
This setup will help you run Llama inference scripts for text and multi-modal tasks directly in Google Colab.
import subprocess
model_name = 'models/my_trained_model'
prompt_text = 'Describe this image'
# Run inference script using subprocess and pass prompt text directly
command = f'python inference.py --model_name {model_name} --prompt_text "{prompt_text}" --use_auditnlg'
subprocess.run(command, shell=True)
Notes:
Modify as Needed: Depending on the script you're using, you might need to adjust parsing or input handling.
Simplicity for Testing: If you're testing, using a short, direct prompt can be faster to debug.
Adjust your approach based on the capabilities and requirements of the script you are working with. If the script does not support direct text prompt input, minor modifications to handle arguments are usually straightforward if you have access to the script.
python
from google.colab import drive
drive.mount('/content/drive')
If this code is intended to be installed as a package, ensure you have completed those steps (like having a setup.py and running pip install -e . in the directory containing it).
By verifying these steps, you should be able to resolve import issues related to the llama_recipes module. Essentially, it's about aligning the module path with Python's expectations for package and module discovery. If you have control over the inference.py file, adding logging or printing statements to debug the path further can be beneficial.
Inside inference.py, ensure relative or absolute imports align with the package structure. For instance:
python
from ...inference.model_utils import load_model, load_peft_model
Verify Package/Directory Names:
Check for any typos or discrepancies in directory names or missing __init__.py files within the Python namespace.
Colab Environment Check:
Since paths can sometimes get misaligned in Colab sessions, verify everything is consistent and rerun setup steps if environments are reset.
Module Installation:
If applicable, assume the directory is treated as an installable package and you've run appropriate commands like pip install -e . in its root, allowing llama_recipes to be recognized as an importable package in Python's path.
After going through these adjustments, running your script should navigate correctly through the module hierarchy, making Python's import system recognize your intended package structure.
model = load_model(model_name, quantization, use_fast_kernels, **kwargs)
if peft_model:
model = load_peft_model(model, peft_model)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
def inference(
user_prompt,
temperature,
top_p,
top_k,
max_new_tokens,
**kwargs,
):
safety_checker = get_safety_checker(
enable_azure_content_safety,
enable_sensitive_topics,
enable_salesforce_content_safety,
enable_llamaguard_content_safety,
)
# Safety check of the user prompt
safety_results = [check(user_prompt) for check in safety_checker]
are_safe = all([r[1] for r in safety_results])
if are_safe:
print("User prompt deemed safe.")
print(f"User prompt:\n{user_prompt}")
else:
print("User prompt deemed unsafe.")
for method, is_safe, report in safety_results:
if not is_safe:
print(method)
print(report)
print("Skipping the inference as the prompt is not safe.")
return # Exit the program with an error status
batch = tokenizer(
user_prompt,
truncation=True,
max_length=max_padding_length,
return_tensors="pt",
)
if is_xpu_available():
batch = {k: v.to("xpu") for k, v in batch.items()}
else:
batch = {k: v.to("cuda") for k, v in batch.items()}
start = time.perf_counter()
with torch.no_grad():
outputs = model.generate(
**batch,
max_new_tokens=max_new_tokens,
do_sample=do_sample,
top_p=top_p,
temperature=temperature,
min_length=min_length,
use_cache=use_cache,
top_k=top_k,
repetition_penalty=repetition_penalty,
length_penalty=length_penalty,
**kwargs,
)
e2e_inference_time = (time.perf_counter() - start) * 1000
print(f"the inference time is {e2e_inference_time} ms")
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Safety check of the model output
safety_results = [
check(output_text, agent_type=AgentType.AGENT, user_prompt=user_prompt)
for check in safety_checker
]
are_safe = all([r[1] for r in safety_results])
if are_safe:
print("User input and model output deemed safe.")
print(f"Model output:\n{output_text}")
return output_text
else:
print("Model output deemed unsafe.")
for method, is_safe, report in safety_results:
if not is_safe:
print(method)
print(report)
return None
if prompt_file is not None:
assert os.path.exists(
prompt_file
), f"Provided Prompt file does not exist {prompt_file}"
with open(prompt_file, "r") as f:
user_prompt = "\n".join(f.readlines())
inference(user_prompt, temperature, top_p, top_k, max_new_tokens)
elif not sys.stdin.isatty():
user_prompt = "\n".join(sys.stdin.readlines())
inference(user_prompt, temperature, top_p, top_k, max_new_tokens)
else:
try:
import gradio as gr
except ImportError:
raise ImportError("This part of the recipe requires gradio. Please run `pip install gradio`")
gr.Interface(
fn=inference,
inputs=[
gr.components.Textbox(
lines=9,
label="User Prompt",
placeholder="none",
),
gr.components.Slider(
minimum=0, maximum=1, value=1.0, label="Temperature"
),
gr.components.Slider(minimum=0, maximum=1, value=1.0, label="Top p"),
gr.components.Slider(
minimum=0, maximum=100, step=1, value=50, label="Top k"
),
gr.components.Slider(
minimum=1, maximum=2000, step=1, value=200, label="Max tokens"
),
],
outputs=[
gr.components.Textbox(
lines=5,
label="Output",
)
],
title="Meta Llama3 Playground",
description="https://github.com/meta-llama/llama-recipes",
).queue().launch(server_name="0.0.0.0", share=share_gradio)
if name == "main":
fire.Fire(main)
Installation as a Package (If Required)
If llama_recipes is structured as a standalone package that you'd like to install, use:
bash
cd /content/llama-recipes
pip install -e .
This command essentially adds the module to the Python environment, allowing you to import it from anywhere.
Module Import Sanity Check
Ensure that the imports at the beginning of the inference.py file match the actual package structure on disk. If they're not valid relative imports, ensure they respect the hierarchy of your directories.
Summary
Carefully verifying and aligning the directory structure, PYTHONPATH, and run commands should resolve module path issues. The main goal is to ensure Python's import system can properly locate the llama_recipes package, recognizing it as a module with valid paths.