Views
No views yet
from transformers import pipeline
qa_model = pipeline("question-answering", model="SaraPiscitelli/roberta-base-qa-v1")
question = "Which name is also used to describe the Amazon rainforest in English?"
context = """The Amazon rainforest (Portuguese: Floresta Amazônica or Amazônia; Spanish: Selva Amazónica, Amazonía or usually Amazonia; French: Forêt amazonienne; Dutch: Amazoneregenwoud), also known in English as Amazonia or the Amazon Jungle, is a moist broadleaf forest that covers most of the Amazon basin of South America. This basin encompasses 7,000,000 square kilometres (2,700,000 sq mi), of which 5,500,000 square kilometres (2,100,000 sq mi) are covered by the rainforest. This region includes territory belonging to nine nations. The majority of the forest is contained within Brazil, with 60% of the rainforest, followed by Peru with 13%, Colombia with 10%, and with minor amounts in Venezuela, Ecuador, Bolivia, Guyana, Suriname and French Guiana. States or departments in four nations contain "Amazonas" in their names. The Amazon represents over half of the planet's remaining rainforests, and comprises the largest and most biodiverse tract of tropical rainforest in the world, with an estimated 390 billion individual trees divided into 16,000 species."""
print(qa_model(question = question, context = context)['answer'])import torch
from typing import List, Optional
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
class InferenceModel:
def __init__(self, model_name_or_checkpoin_path: str,
tokenizer_name: Optional[str] = None,
device_type: Optional[str] = None) -> List[str]:
if tokenizer_name is None:
tokenizer_name = model_name_or_checkpoin_path
if device_type is None:
device_type = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
self.model = AutoModelForQuestionAnswering.from_pretrained(model_name_or_checkpoin_path, device_map=device_type)
self.model.eval()
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_checkpoin_path)
def inference(self, questions: List[str], contexts: List[str]) -> List[str]:
inputs = self.tokenizer(questions, contexts,
padding="longest",
return_tensors="pt").to(self.model.device)
with torch.no_grad():
logits = self.model(**inputs)
# logits.start_logits.shape == (batch_size, input_length) = inputs['input_ids'].shape
# logits.end_logits.shape == (batch_size, input_length) = inputs['input_ids'].shape
answer_start_index: List[int] = logits.start_logits.argmax(dim=-1).tolist()
answer_end_index: List[int] = logits.end_logits.argmax(dim=-1).tolist()
answer_tokens: List[str] = [self.tokenizer.decode(inputs.input_ids[i, answer_start_index[i] : answer_end_index[i] + 1])
for i in range(len(questions))]
return answer_tokens
model = InferenceModel("SaraPiscitelli/roberta-base-qa-v1")
question = "Which name is also used to describe the Amazon rainforest in English?"
context = """The Amazon rainforest (Portuguese: Floresta Amazônica or Amazônia; Spanish: Selva Amazónica, Amazonía or usually Amazonia; French: Forêt amazonienne; Dutch: Amazoneregenwoud), also known in English as Amazonia or the Amazon Jungle, is a moist broadleaf forest that covers most of the Amazon basin of South America. This basin encompasses 7,000,000 square kilometres (2,700,000 sq mi), of which 5,500,000 square kilometres (2,100,000 sq mi) are covered by the rainforest. This region includes territory belonging to nine nations. The majority of the forest is contained within Brazil, with 60% of the rainforest, followed by Peru with 13%, Colombia with 10%, and with minor amounts in Venezuela, Ecuador, Bolivia, Guyana, Suriname and French Guiana. States or departments in four nations contain "Amazonas" in their names. The Amazon represents over half of the planet's remaining rainforests, and comprises the largest and most biodiverse tract of tropical rainforest in the world, with an estimated 390 billion individual trees divided into 16,000 species."""
print(model.inference(questions=[question], contexts=[context])[0])from datasets import load_dataset
squad = load_dataset("squad")
squad['train'] = squad['train'].select(range(30000))
squad['test'] = squad['validation']
squad['validation'] = squad['validation'].select(range(2000))from datasets import load_dataset
squad = load_dataset("squad")
squad['test'] = squad['validation'] import evaluate
metric_eval = evaluate.load("squad_v2")