hugging face saved model inference
hi , i am using this notebook for doing inference locally '/NeMo/tutorials/llm/embedding/llama_embedding.ipynb' . it has example shown for nemo ckpt. can anyone help on how to use hf ckpt for doing inference? I am using 80gb a100 still i m getting memory error when i am using llama32_1b embedding model.
thanks
Hi @riyajatar37003 , if you convert the NeMO ckpt to hf ckpt using the export_ckpt, you should be able to run inference on HF side using script similar to below:
import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
model_name = 'YOUR_TRAINED_LLAMA_EMBEDDING_MODEL'
prefix_query = "query: "
prefix_passge = "passage: "
def average_pool(
last_hidden_states: Tensor,
attention_mask: Tensor
) -> Tensor:
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
def extract_emb(
text
):
batch_dict = tokenizer(text, padding=True, truncation=True, return_tensors='pt')
outputs = model(**batch_dict)
embeddings = average_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
embeddings = F.normalize(embeddings, p=2, dim=1)
return(embeddings)
# Each input text should start with "query: " or "passage: ".
# For tasks other than retrieval, you can simply use the "query: " prefix.
queries = ['how much protein should a female eat', 'summit define']
passages = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
]
queries = [f"{prefix_query} {query}" for query in queries]
passages = [f"{prefix_passge} {passage}" for passage in passages]
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
# Tokenize the input texts
embeddings_queries = extract_emb(queries)
embeddings_passages = extract_emb(passages)
scores = (embeddings_queries @ embeddings_passages.T)
print(scores.tolist())
# [[0.5038352608680725, -0.024130651727318764], [-0.021166358143091202, 0.40186744928359985]]
Thanks let me try this
Get Outlook for Androidhttps://aka.ms/AAb9ysg
From: Ao Tang @.> Sent: Friday, June 13, 2025 10:53:54 PM To: NVIDIA/NeMo @.> Cc: Riyaj Atar @.>; Mention @.> Subject: Re: [NVIDIA/NeMo] hugging face saved model inference (Issue #13891)
[https://image-tracking-service.us-1.mimecastcybergraph.com/v1/image?imageData=o54MERlXQujAzTm6crqpZJck1GAH%2FzympvlZJzZ%2BpOTFXGbOaPFdbs7F9svu2veXVPFRgvgxh2Ncvy0PZ6C7XR4uxhSe9YvUVHLzVXZ5mW4TzWw%2F6sCsr%2FpZ1H2kMCukxt5xDTM094eD%2BBKadXySH%2FFN71kkCnYHTcpKAv8pjRCHo8RXLfugpKeAWMVPSHQRvsPM5%2FrPgHuH9QpWUxfsR6mBGaCIvW3CR0tmxQL0qMJCeNNW5ftQVQTfVVDXCqBE0j2MN%2Fz4fyJo%2B7OOsAHTZV%2Bbv%2F0%3D] [External Email]
suiyoubi left a comment (NVIDIA/NeMo#13891)https://github.com/NVIDIA/NeMo/issues/13891#issuecomment-2971025467
Hi @riyajatar37003https://github.com/riyajatar37003 , if you convert the NeMO ckpt to hf ckpt using the export_ckpt, you should be able to run inference on HF side using script similar to below:
import torch.nn.functional as F
from torch import Tensor from transformers import AutoTokenizer, AutoModel
model_name = 'YOUR_TRAINED_LLAMA_EMBEDDING_MODEL' prefix_query = "query: " prefix_passge = "passage: "
def average_pool( last_hidden_states: Tensor, attention_mask: Tensor ) -> Tensor: last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0) return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
def extract_emb( text ): batch_dict = tokenizer(text, padding=True, truncation=True, return_tensors='pt') outputs = model(**batch_dict) embeddings = average_pool(outputs.last_hidden_state, batch_dict['attention_mask']) embeddings = F.normalize(embeddings, p=2, dim=1) return(embeddings)
Each input text should start with "query: " or "passage: ".
For tasks other than retrieval, you can simply use the "query: " prefix.
queries = ['how much protein should a female eat', 'summit define'] passages = [ "As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.", "Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments." ]
queries = [f"{prefix_query} {query}" for query in queries] passages = [f"{prefix_passge} {passage}" for passage in passages]
tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
Tokenize the input texts
embeddings_queries = extract_emb(queries) embeddings_passages = extract_emb(passages)
scores = (embeddings_queries @ embeddings_passages.T) print(scores.tolist())
[[0.5038352608680725, -0.024130651727318764], [-0.021166358143091202, 0.40186744928359985]]
— Reply to this email directly, view it on GitHubhttps://github.com/NVIDIA/NeMo/issues/13891#issuecomment-2971025467, or unsubscribehttps://github.com/notifications/unsubscribe-auth/BIJR5XSIZICUJX3MWP54SLT3DMCKVAVCNFSM6AAAAAB7DAJTUWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDSNZRGAZDKNBWG4. You are receiving this because you were mentioned.Message ID: @.***>
This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.
This issue was closed because it has been inactive for 7 days since being marked as stale.