sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
mem0ai/mem0:evaluation/evals.py | import argparse
import concurrent.futures
import json
import threading
from collections import defaultdict
from metrics.llm_judge import evaluate_llm_judge
from metrics.utils import calculate_bleu_scores, calculate_metrics
from tqdm import tqdm
def process_item(item_data):
k, v = item_data
local_results = defaultdict(list)
for item in v:
gt_answer = str(item["answer"])
pred_answer = str(item["response"])
category = str(item["category"])
question = str(item["question"])
# Skip category 5
if category == "5":
continue
metrics = calculate_metrics(pred_answer, gt_answer)
bleu_scores = calculate_bleu_scores(pred_answer, gt_answer)
llm_score = evaluate_llm_judge(question, gt_answer, pred_answer)
local_results[k].append(
{
"question": question,
"answer": gt_answer,
"response": pred_answer,
"category": category,
"bleu_score": bleu_scores["bleu1"],
"f1_score": metrics["f1"],
"llm_score": llm_score,
}
)
return local_results
def main():
parser = argparse.ArgumentParser(description="Evaluate RAG results")
parser.add_argument(
"--input_file", type=str, default="results/rag_results_500_k1.json", help="Path to the input dataset file"
)
parser.add_argument(
"--output_file", type=str, default="evaluation_metrics.json", help="Path to save the evaluation results"
)
parser.add_argument("--max_workers", type=int, default=10, help="Maximum number of worker threads")
args = parser.parse_args()
with open(args.input_file, "r") as f:
data = json.load(f)
results = defaultdict(list)
results_lock = threading.Lock()
# Use ThreadPoolExecutor with specified workers
with concurrent.futures.ThreadPoolExecutor(max_workers=args.max_workers) as executor:
futures = [executor.submit(process_item, item_data) for item_data in data.items()]
for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures)):
local_results = future.result()
with results_lock:
for k, items in local_results.items():
results[k].extend(items)
# Save results to JSON file
with open(args.output_file, "w") as f:
json.dump(results, f, indent=4)
print(f"Results saved to {args.output_file}")
if __name__ == "__main__":
main()
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/evals.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
mem0ai/mem0:evaluation/generate_scores.py | import json
import pandas as pd
# Load the evaluation metrics data
with open("evaluation_metrics.json", "r") as f:
data = json.load(f)
# Flatten the data into a list of question items
all_items = []
for key in data:
all_items.extend(data[key])
# Convert to DataFrame
df = pd.DataFrame(all_items)
# Convert category to numeric type
df["category"] = pd.to_numeric(df["category"])
# Calculate mean scores by category
result = df.groupby("category").agg({"bleu_score": "mean", "f1_score": "mean", "llm_score": "mean"}).round(4)
# Add count of questions per category
result["count"] = df.groupby("category").size()
# Print the results
print("Mean Scores Per Category:")
print(result)
# Calculate overall means
overall_means = df.agg({"bleu_score": "mean", "f1_score": "mean", "llm_score": "mean"}).round(4)
print("\nOverall Mean Scores:")
print(overall_means)
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/generate_scores.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
mem0ai/mem0:evaluation/metrics/llm_judge.py | import argparse
import json
from collections import defaultdict
import numpy as np
from openai import OpenAI
from mem0.memory.utils import extract_json
client = OpenAI()
ACCURACY_PROMPT = """
Your task is to label an answer to a question as ’CORRECT’ or ’WRONG’. You will be given the following data:
(1) a question (posed by one user to another user),
(2) a ’gold’ (ground truth) answer,
(3) a generated answer
which you will score as CORRECT/WRONG.
The point of the question is to ask about something one user should know about the other user based on their prior conversations.
The gold answer will usually be a concise and short answer that includes the referenced topic, for example:
Question: Do you remember what I got the last time I went to Hawaii?
Gold answer: A shell necklace
The generated answer might be much longer, but you should be generous with your grading - as long as it touches on the same topic as the gold answer, it should be counted as CORRECT.
For time related questions, the gold answer will be a specific date, month, year, etc. The generated answer might be much longer or use relative time references (like "last Tuesday" or "next month"), but you should be generous with your grading - as long as it refers to the same date or time period as the gold answer, it should be counted as CORRECT. Even if the format differs (e.g., "May 7th" vs "7 May"), consider it CORRECT if it's the same date.
Now it's time for the real question:
Question: {question}
Gold answer: {gold_answer}
Generated answer: {generated_answer}
First, provide a short (one sentence) explanation of your reasoning, then finish with CORRECT or WRONG.
Do NOT include both CORRECT and WRONG in your response, or it will break the evaluation script.
Just return the label CORRECT or WRONG in a json format with the key as "label".
"""
def evaluate_llm_judge(question, gold_answer, generated_answer):
"""Evaluate the generated answer against the gold answer using an LLM judge."""
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": ACCURACY_PROMPT.format(
question=question, gold_answer=gold_answer, generated_answer=generated_answer
),
}
],
response_format={"type": "json_object"},
temperature=0.0,
)
label = json.loads(extract_json(response.choices[0].message.content))["label"]
return 1 if label == "CORRECT" else 0
def main():
"""Main function to evaluate RAG results using LLM judge."""
parser = argparse.ArgumentParser(description="Evaluate RAG results using LLM judge")
parser.add_argument(
"--input_file",
type=str,
default="results/default_run_v4_k30_new_graph.json",
help="Path to the input dataset file",
)
args = parser.parse_args()
dataset_path = args.input_file
output_path = f"results/llm_judge_{dataset_path.split('/')[-1]}"
with open(dataset_path, "r") as f:
data = json.load(f)
LLM_JUDGE = defaultdict(list)
RESULTS = defaultdict(list)
index = 0
for k, v in data.items():
for x in v:
question = x["question"]
gold_answer = x["answer"]
generated_answer = x["response"]
category = x["category"]
# Skip category 5
if int(category) == 5:
continue
# Evaluate the answer
label = evaluate_llm_judge(question, gold_answer, generated_answer)
LLM_JUDGE[category].append(label)
# Store the results
RESULTS[index].append(
{
"question": question,
"gt_answer": gold_answer,
"response": generated_answer,
"category": category,
"llm_label": label,
}
)
# Save intermediate results
with open(output_path, "w") as f:
json.dump(RESULTS, f, indent=4)
# Print current accuracy for all categories
print("All categories accuracy:")
for cat, results in LLM_JUDGE.items():
if results: # Only print if there are results for this category
print(f" Category {cat}: {np.mean(results):.4f} ({sum(results)}/{len(results)})")
print("------------------------------------------")
index += 1
# Save final results
with open(output_path, "w") as f:
json.dump(RESULTS, f, indent=4)
# Print final summary
print("PATH: ", dataset_path)
print("------------------------------------------")
for k, v in LLM_JUDGE.items():
print(k, np.mean(v))
if __name__ == "__main__":
main()
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/metrics/llm_judge.py",
"license": "Apache License 2.0",
"lines": 103,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/metrics/utils.py | """
Borrowed from https://github.com/WujiangXu/AgenticMemory/blob/main/utils.py
@article{xu2025mem,
title={A-mem: Agentic memory for llm agents},
author={Xu, Wujiang and Liang, Zujie and Mei, Kai and Gao, Hang and Tan, Juntao
and Zhang, Yongfeng},
journal={arXiv preprint arXiv:2502.12110},
year={2025}
}
"""
import statistics
from collections import defaultdict
from typing import Dict, List, Union
import nltk
from bert_score import score as bert_score
from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu
from nltk.translate.meteor_score import meteor_score
from rouge_score import rouge_scorer
from sentence_transformers import SentenceTransformer
# from load_dataset import load_locomo_dataset, QA, Turn, Session, Conversation
from sentence_transformers.util import pytorch_cos_sim
# Download required NLTK data
try:
nltk.download("punkt", quiet=True)
nltk.download("wordnet", quiet=True)
except Exception as e:
print(f"Error downloading NLTK data: {e}")
# Initialize SentenceTransformer model (this will be reused)
try:
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
except Exception as e:
print(f"Warning: Could not load SentenceTransformer model: {e}")
sentence_model = None
def simple_tokenize(text):
"""Simple tokenization function."""
# Convert to string if not already
text = str(text)
return text.lower().replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ").split()
def calculate_rouge_scores(prediction: str, reference: str) -> Dict[str, float]:
"""Calculate ROUGE scores for prediction against reference."""
scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
scores = scorer.score(reference, prediction)
return {
"rouge1_f": scores["rouge1"].fmeasure,
"rouge2_f": scores["rouge2"].fmeasure,
"rougeL_f": scores["rougeL"].fmeasure,
}
def calculate_bleu_scores(prediction: str, reference: str) -> Dict[str, float]:
"""Calculate BLEU scores with different n-gram settings."""
pred_tokens = nltk.word_tokenize(prediction.lower())
ref_tokens = [nltk.word_tokenize(reference.lower())]
weights_list = [(1, 0, 0, 0), (0.5, 0.5, 0, 0), (0.33, 0.33, 0.33, 0), (0.25, 0.25, 0.25, 0.25)]
smooth = SmoothingFunction().method1
scores = {}
for n, weights in enumerate(weights_list, start=1):
try:
score = sentence_bleu(ref_tokens, pred_tokens, weights=weights, smoothing_function=smooth)
except Exception as e:
print(f"Error calculating BLEU score: {e}")
score = 0.0
scores[f"bleu{n}"] = score
return scores
def calculate_bert_scores(prediction: str, reference: str) -> Dict[str, float]:
"""Calculate BERTScore for semantic similarity."""
try:
P, R, F1 = bert_score([prediction], [reference], lang="en", verbose=False)
return {"bert_precision": P.item(), "bert_recall": R.item(), "bert_f1": F1.item()}
except Exception as e:
print(f"Error calculating BERTScore: {e}")
return {"bert_precision": 0.0, "bert_recall": 0.0, "bert_f1": 0.0}
def calculate_meteor_score(prediction: str, reference: str) -> float:
"""Calculate METEOR score for the prediction."""
try:
return meteor_score([reference.split()], prediction.split())
except Exception as e:
print(f"Error calculating METEOR score: {e}")
return 0.0
def calculate_sentence_similarity(prediction: str, reference: str) -> float:
"""Calculate sentence embedding similarity using SentenceBERT."""
if sentence_model is None:
return 0.0
try:
# Encode sentences
embedding1 = sentence_model.encode([prediction], convert_to_tensor=True)
embedding2 = sentence_model.encode([reference], convert_to_tensor=True)
# Calculate cosine similarity
similarity = pytorch_cos_sim(embedding1, embedding2).item()
return float(similarity)
except Exception as e:
print(f"Error calculating sentence similarity: {e}")
return 0.0
def calculate_metrics(prediction: str, reference: str) -> Dict[str, float]:
"""Calculate comprehensive evaluation metrics for a prediction."""
# Handle empty or None values
if not prediction or not reference:
return {
"exact_match": 0,
"f1": 0.0,
"rouge1_f": 0.0,
"rouge2_f": 0.0,
"rougeL_f": 0.0,
"bleu1": 0.0,
"bleu2": 0.0,
"bleu3": 0.0,
"bleu4": 0.0,
"bert_f1": 0.0,
"meteor": 0.0,
"sbert_similarity": 0.0,
}
# Convert to strings if they're not already
prediction = str(prediction).strip()
reference = str(reference).strip()
# Calculate exact match
exact_match = int(prediction.lower() == reference.lower())
# Calculate token-based F1 score
pred_tokens = set(simple_tokenize(prediction))
ref_tokens = set(simple_tokenize(reference))
common_tokens = pred_tokens & ref_tokens
if not pred_tokens or not ref_tokens:
f1 = 0.0
else:
precision = len(common_tokens) / len(pred_tokens)
recall = len(common_tokens) / len(ref_tokens)
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
# Calculate all scores
bleu_scores = calculate_bleu_scores(prediction, reference)
# Combine all metrics
metrics = {
"exact_match": exact_match,
"f1": f1,
**bleu_scores,
}
return metrics
def aggregate_metrics(
all_metrics: List[Dict[str, float]], all_categories: List[int]
) -> Dict[str, Dict[str, Union[float, Dict[str, float]]]]:
"""Calculate aggregate statistics for all metrics, split by category."""
if not all_metrics:
return {}
# Initialize aggregates for overall and per-category metrics
aggregates = defaultdict(list)
category_aggregates = defaultdict(lambda: defaultdict(list))
# Collect all values for each metric, both overall and per category
for metrics, category in zip(all_metrics, all_categories):
for metric_name, value in metrics.items():
aggregates[metric_name].append(value)
category_aggregates[category][metric_name].append(value)
# Calculate statistics for overall metrics
results = {"overall": {}}
for metric_name, values in aggregates.items():
results["overall"][metric_name] = {
"mean": statistics.mean(values),
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
"median": statistics.median(values),
"min": min(values),
"max": max(values),
"count": len(values),
}
# Calculate statistics for each category
for category in sorted(category_aggregates.keys()):
results[f"category_{category}"] = {}
for metric_name, values in category_aggregates[category].items():
if values: # Only calculate if we have values for this category
results[f"category_{category}"][metric_name] = {
"mean": statistics.mean(values),
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
"median": statistics.median(values),
"min": min(values),
"max": max(values),
"count": len(values),
}
return results
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/metrics/utils.py",
"license": "Apache License 2.0",
"lines": 172,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/prompts.py | ANSWER_PROMPT_GRAPH = """
You are an intelligent memory assistant tasked with retrieving accurate information from
conversation memories.
# CONTEXT:
You have access to memories from two speakers in a conversation. These memories contain
timestamped information that may be relevant to answering the question. You also have
access to knowledge graph relations for each user, showing connections between entities,
concepts, and events relevant to that user.
# INSTRUCTIONS:
1. Carefully analyze all provided memories from both speakers
2. Pay special attention to the timestamps to determine the answer
3. If the question asks about a specific event or fact, look for direct evidence in the
memories
4. If the memories contain contradictory information, prioritize the most recent memory
5. If there is a question about time references (like "last year", "two months ago",
etc.), calculate the actual date based on the memory timestamp. For example, if a
memory from 4 May 2022 mentions "went to India last year," then the trip occurred
in 2021.
6. Always convert relative time references to specific dates, months, or years. For
example, convert "last year" to "2022" or "two months ago" to "March 2023" based
on the memory timestamp. Ignore the reference while answering the question.
7. Focus only on the content of the memories from both speakers. Do not confuse
character names mentioned in memories with the actual users who created those
memories.
8. The answer should be less than 5-6 words.
9. Use the knowledge graph relations to understand the user's knowledge network and
identify important relationships between entities in the user's world.
# APPROACH (Think step by step):
1. First, examine all memories that contain information related to the question
2. Examine the timestamps and content of these memories carefully
3. Look for explicit mentions of dates, times, locations, or events that answer the
question
4. If the answer requires calculation (e.g., converting relative time references),
show your work
5. Analyze the knowledge graph relations to understand the user's knowledge context
6. Formulate a precise, concise answer based solely on the evidence in the memories
7. Double-check that your answer directly addresses the question asked
8. Ensure your final answer is specific and avoids vague time references
Memories for user {{speaker_1_user_id}}:
{{speaker_1_memories}}
Relations for user {{speaker_1_user_id}}:
{{speaker_1_graph_memories}}
Memories for user {{speaker_2_user_id}}:
{{speaker_2_memories}}
Relations for user {{speaker_2_user_id}}:
{{speaker_2_graph_memories}}
Question: {{question}}
Answer:
"""
ANSWER_PROMPT = """
You are an intelligent memory assistant tasked with retrieving accurate information from conversation memories.
# CONTEXT:
You have access to memories from two speakers in a conversation. These memories contain
timestamped information that may be relevant to answering the question.
# INSTRUCTIONS:
1. Carefully analyze all provided memories from both speakers
2. Pay special attention to the timestamps to determine the answer
3. If the question asks about a specific event or fact, look for direct evidence in the memories
4. If the memories contain contradictory information, prioritize the most recent memory
5. If there is a question about time references (like "last year", "two months ago", etc.),
calculate the actual date based on the memory timestamp. For example, if a memory from
4 May 2022 mentions "went to India last year," then the trip occurred in 2021.
6. Always convert relative time references to specific dates, months, or years. For example,
convert "last year" to "2022" or "two months ago" to "March 2023" based on the memory
timestamp. Ignore the reference while answering the question.
7. Focus only on the content of the memories from both speakers. Do not confuse character
names mentioned in memories with the actual users who created those memories.
8. The answer should be less than 5-6 words.
# APPROACH (Think step by step):
1. First, examine all memories that contain information related to the question
2. Examine the timestamps and content of these memories carefully
3. Look for explicit mentions of dates, times, locations, or events that answer the question
4. If the answer requires calculation (e.g., converting relative time references), show your work
5. Formulate a precise, concise answer based solely on the evidence in the memories
6. Double-check that your answer directly addresses the question asked
7. Ensure your final answer is specific and avoids vague time references
Memories for user {{speaker_1_user_id}}:
{{speaker_1_memories}}
Memories for user {{speaker_2_user_id}}:
{{speaker_2_memories}}
Question: {{question}}
Answer:
"""
ANSWER_PROMPT_ZEP = """
You are an intelligent memory assistant tasked with retrieving accurate information from conversation memories.
# CONTEXT:
You have access to memories from a conversation. These memories contain
timestamped information that may be relevant to answering the question.
# INSTRUCTIONS:
1. Carefully analyze all provided memories
2. Pay special attention to the timestamps to determine the answer
3. If the question asks about a specific event or fact, look for direct evidence in the memories
4. If the memories contain contradictory information, prioritize the most recent memory
5. If there is a question about time references (like "last year", "two months ago", etc.),
calculate the actual date based on the memory timestamp. For example, if a memory from
4 May 2022 mentions "went to India last year," then the trip occurred in 2021.
6. Always convert relative time references to specific dates, months, or years. For example,
convert "last year" to "2022" or "two months ago" to "March 2023" based on the memory
timestamp. Ignore the reference while answering the question.
7. Focus only on the content of the memories. Do not confuse character
names mentioned in memories with the actual users who created those memories.
8. The answer should be less than 5-6 words.
# APPROACH (Think step by step):
1. First, examine all memories that contain information related to the question
2. Examine the timestamps and content of these memories carefully
3. Look for explicit mentions of dates, times, locations, or events that answer the question
4. If the answer requires calculation (e.g., converting relative time references), show your work
5. Formulate a precise, concise answer based solely on the evidence in the memories
6. Double-check that your answer directly addresses the question asked
7. Ensure your final answer is specific and avoids vague time references
Memories:
{{memories}}
Question: {{question}}
Answer:
"""
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/prompts.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
mem0ai/mem0:evaluation/run_experiments.py | import argparse
import os
from src.langmem import LangMemManager
from src.memzero.add import MemoryADD
from src.memzero.search import MemorySearch
from src.openai.predict import OpenAIPredict
from src.rag import RAGManager
from src.utils import METHODS, TECHNIQUES
from src.zep.add import ZepAdd
from src.zep.search import ZepSearch
class Experiment:
def __init__(self, technique_type, chunk_size):
self.technique_type = technique_type
self.chunk_size = chunk_size
def run(self):
print(f"Running experiment with technique: {self.technique_type}, chunk size: {self.chunk_size}")
def main():
parser = argparse.ArgumentParser(description="Run memory experiments")
parser.add_argument("--technique_type", choices=TECHNIQUES, default="mem0", help="Memory technique to use")
parser.add_argument("--method", choices=METHODS, default="add", help="Method to use")
parser.add_argument("--chunk_size", type=int, default=1000, help="Chunk size for processing")
parser.add_argument("--output_folder", type=str, default="results/", help="Output path for results")
parser.add_argument("--top_k", type=int, default=30, help="Number of top memories to retrieve")
parser.add_argument("--filter_memories", action="store_true", default=False, help="Whether to filter memories")
parser.add_argument("--is_graph", action="store_true", default=False, help="Whether to use graph-based search")
parser.add_argument("--num_chunks", type=int, default=1, help="Number of chunks to process")
args = parser.parse_args()
# Add your experiment logic here
print(f"Running experiments with technique: {args.technique_type}, chunk size: {args.chunk_size}")
if args.technique_type == "mem0":
if args.method == "add":
memory_manager = MemoryADD(data_path="dataset/locomo10.json", is_graph=args.is_graph)
memory_manager.process_all_conversations()
elif args.method == "search":
output_file_path = os.path.join(
args.output_folder,
f"mem0_results_top_{args.top_k}_filter_{args.filter_memories}_graph_{args.is_graph}.json",
)
memory_searcher = MemorySearch(output_file_path, args.top_k, args.filter_memories, args.is_graph)
memory_searcher.process_data_file("dataset/locomo10.json")
elif args.technique_type == "rag":
output_file_path = os.path.join(args.output_folder, f"rag_results_{args.chunk_size}_k{args.num_chunks}.json")
rag_manager = RAGManager(data_path="dataset/locomo10_rag.json", chunk_size=args.chunk_size, k=args.num_chunks)
rag_manager.process_all_conversations(output_file_path)
elif args.technique_type == "langmem":
output_file_path = os.path.join(args.output_folder, "langmem_results.json")
langmem_manager = LangMemManager(dataset_path="dataset/locomo10_rag.json")
langmem_manager.process_all_conversations(output_file_path)
elif args.technique_type == "zep":
if args.method == "add":
zep_manager = ZepAdd(data_path="dataset/locomo10.json")
zep_manager.process_all_conversations("1")
elif args.method == "search":
output_file_path = os.path.join(args.output_folder, "zep_search_results.json")
zep_manager = ZepSearch()
zep_manager.process_data_file("dataset/locomo10.json", "1", output_file_path)
elif args.technique_type == "openai":
output_file_path = os.path.join(args.output_folder, "openai_results.json")
openai_manager = OpenAIPredict()
openai_manager.process_data_file("dataset/locomo10.json", output_file_path)
else:
raise ValueError(f"Invalid technique type: {args.technique_type}")
if __name__ == "__main__":
main()
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/run_experiments.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/langmem.py | import json
import multiprocessing as mp
import os
import time
from collections import defaultdict
from dotenv import load_dotenv
from jinja2 import Template
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from langgraph.store.memory import InMemoryStore
from langgraph.utils.config import get_store
from langmem import create_manage_memory_tool, create_search_memory_tool
from openai import OpenAI
from prompts import ANSWER_PROMPT
from tqdm import tqdm
load_dotenv()
client = OpenAI()
ANSWER_PROMPT_TEMPLATE = Template(ANSWER_PROMPT)
def get_answer(question, speaker_1_user_id, speaker_1_memories, speaker_2_user_id, speaker_2_memories):
prompt = ANSWER_PROMPT_TEMPLATE.render(
question=question,
speaker_1_user_id=speaker_1_user_id,
speaker_1_memories=speaker_1_memories,
speaker_2_user_id=speaker_2_user_id,
speaker_2_memories=speaker_2_memories,
)
t1 = time.time()
response = client.chat.completions.create(
model=os.getenv("MODEL"), messages=[{"role": "system", "content": prompt}], temperature=0.0
)
t2 = time.time()
return response.choices[0].message.content, t2 - t1
def prompt(state):
"""Prepare the messages for the LLM."""
store = get_store()
memories = store.search(
("memories",),
query=state["messages"][-1].content,
)
system_msg = f"""You are a helpful assistant.
## Memories
<memories>
{memories}
</memories>
"""
return [{"role": "system", "content": system_msg}, *state["messages"]]
class LangMem:
def __init__(
self,
):
self.store = InMemoryStore(
index={
"dims": 1536,
"embed": f"openai:{os.getenv('EMBEDDING_MODEL')}",
}
)
self.checkpointer = MemorySaver() # Checkpoint graph state
self.agent = create_react_agent(
f"openai:{os.getenv('MODEL')}",
prompt=prompt,
tools=[
create_manage_memory_tool(namespace=("memories",)),
create_search_memory_tool(namespace=("memories",)),
],
store=self.store,
checkpointer=self.checkpointer,
)
def add_memory(self, message, config):
return self.agent.invoke({"messages": [{"role": "user", "content": message}]}, config=config)
def search_memory(self, query, config):
try:
t1 = time.time()
response = self.agent.invoke({"messages": [{"role": "user", "content": query}]}, config=config)
t2 = time.time()
return response["messages"][-1].content, t2 - t1
except Exception as e:
print(f"Error in search_memory: {e}")
return "", t2 - t1
class LangMemManager:
def __init__(self, dataset_path):
self.dataset_path = dataset_path
with open(self.dataset_path, "r") as f:
self.data = json.load(f)
def process_all_conversations(self, output_file_path):
OUTPUT = defaultdict(list)
# Process conversations in parallel with multiple workers
def process_conversation(key_value_pair):
key, value = key_value_pair
result = defaultdict(list)
chat_history = value["conversation"]
questions = value["question"]
agent1 = LangMem()
agent2 = LangMem()
config = {"configurable": {"thread_id": f"thread-{key}"}}
speakers = set()
# Identify speakers
for conv in chat_history:
speakers.add(conv["speaker"])
if len(speakers) != 2:
raise ValueError(f"Expected 2 speakers, got {len(speakers)}")
speaker1 = list(speakers)[0]
speaker2 = list(speakers)[1]
# Add memories for each message
for conv in tqdm(chat_history, desc=f"Processing messages {key}", leave=False):
message = f"{conv['timestamp']} | {conv['speaker']}: {conv['text']}"
if conv["speaker"] == speaker1:
agent1.add_memory(message, config)
elif conv["speaker"] == speaker2:
agent2.add_memory(message, config)
else:
raise ValueError(f"Expected speaker1 or speaker2, got {conv['speaker']}")
# Process questions
for q in tqdm(questions, desc=f"Processing questions {key}", leave=False):
category = q["category"]
if int(category) == 5:
continue
answer = q["answer"]
question = q["question"]
response1, speaker1_memory_time = agent1.search_memory(question, config)
response2, speaker2_memory_time = agent2.search_memory(question, config)
generated_answer, response_time = get_answer(question, speaker1, response1, speaker2, response2)
result[key].append(
{
"question": question,
"answer": answer,
"response1": response1,
"response2": response2,
"category": category,
"speaker1_memory_time": speaker1_memory_time,
"speaker2_memory_time": speaker2_memory_time,
"response_time": response_time,
"response": generated_answer,
}
)
return result
# Use multiprocessing to process conversations in parallel
with mp.Pool(processes=10) as pool:
results = list(
tqdm(
pool.imap(process_conversation, list(self.data.items())),
total=len(self.data),
desc="Processing conversations",
)
)
# Combine results from all workers
for result in results:
for key, items in result.items():
OUTPUT[key].extend(items)
# Save final results
with open(output_file_path, "w") as f:
json.dump(OUTPUT, f, indent=4)
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/langmem.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/memzero/add.py | import json
import os
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from dotenv import load_dotenv
from tqdm import tqdm
from mem0 import MemoryClient
load_dotenv()
# Update custom instructions
custom_instructions = """
Generate personal memories that follow these guidelines:
1. Each memory should be self-contained with complete context, including:
- The person's name, do not use "user" while creating memories
- Personal details (career aspirations, hobbies, life circumstances)
- Emotional states and reactions
- Ongoing journeys or future plans
- Specific dates when events occurred
2. Include meaningful personal narratives focusing on:
- Identity and self-acceptance journeys
- Family planning and parenting
- Creative outlets and hobbies
- Mental health and self-care activities
- Career aspirations and education goals
- Important life events and milestones
3. Make each memory rich with specific details rather than general statements
- Include timeframes (exact dates when possible)
- Name specific activities (e.g., "charity race for mental health" rather than just "exercise")
- Include emotional context and personal growth elements
4. Extract memories only from user messages, not incorporating assistant responses
5. Format each memory as a paragraph with a clear narrative structure that captures the person's experience, challenges, and aspirations
"""
class MemoryADD:
def __init__(self, data_path=None, batch_size=2, is_graph=False):
self.mem0_client = MemoryClient(
api_key=os.getenv("MEM0_API_KEY"),
org_id=os.getenv("MEM0_ORGANIZATION_ID"),
project_id=os.getenv("MEM0_PROJECT_ID"),
)
self.mem0_client.update_project(custom_instructions=custom_instructions)
self.batch_size = batch_size
self.data_path = data_path
self.data = None
self.is_graph = is_graph
if data_path:
self.load_data()
def load_data(self):
with open(self.data_path, "r") as f:
self.data = json.load(f)
return self.data
def add_memory(self, user_id, message, metadata, retries=3):
for attempt in range(retries):
try:
_ = self.mem0_client.add(
message, user_id=user_id, version="v2", metadata=metadata, enable_graph=self.is_graph
)
return
except Exception as e:
if attempt < retries - 1:
time.sleep(1) # Wait before retrying
continue
else:
raise e
def add_memories_for_speaker(self, speaker, messages, timestamp, desc):
for i in tqdm(range(0, len(messages), self.batch_size), desc=desc):
batch_messages = messages[i : i + self.batch_size]
self.add_memory(speaker, batch_messages, metadata={"timestamp": timestamp})
def process_conversation(self, item, idx):
conversation = item["conversation"]
speaker_a = conversation["speaker_a"]
speaker_b = conversation["speaker_b"]
speaker_a_user_id = f"{speaker_a}_{idx}"
speaker_b_user_id = f"{speaker_b}_{idx}"
# delete all memories for the two users
self.mem0_client.delete_all(user_id=speaker_a_user_id)
self.mem0_client.delete_all(user_id=speaker_b_user_id)
for key in conversation.keys():
if key in ["speaker_a", "speaker_b"] or "date" in key or "timestamp" in key:
continue
date_time_key = key + "_date_time"
timestamp = conversation[date_time_key]
chats = conversation[key]
messages = []
messages_reverse = []
for chat in chats:
if chat["speaker"] == speaker_a:
messages.append({"role": "user", "content": f"{speaker_a}: {chat['text']}"})
messages_reverse.append({"role": "assistant", "content": f"{speaker_a}: {chat['text']}"})
elif chat["speaker"] == speaker_b:
messages.append({"role": "assistant", "content": f"{speaker_b}: {chat['text']}"})
messages_reverse.append({"role": "user", "content": f"{speaker_b}: {chat['text']}"})
else:
raise ValueError(f"Unknown speaker: {chat['speaker']}")
# add memories for the two users on different threads
thread_a = threading.Thread(
target=self.add_memories_for_speaker,
args=(speaker_a_user_id, messages, timestamp, "Adding Memories for Speaker A"),
)
thread_b = threading.Thread(
target=self.add_memories_for_speaker,
args=(speaker_b_user_id, messages_reverse, timestamp, "Adding Memories for Speaker B"),
)
thread_a.start()
thread_b.start()
thread_a.join()
thread_b.join()
print("Messages added successfully")
def process_all_conversations(self, max_workers=10):
if not self.data:
raise ValueError("No data loaded. Please set data_path and call load_data() first.")
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(self.process_conversation, item, idx) for idx, item in enumerate(self.data)]
for future in futures:
future.result()
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/memzero/add.py",
"license": "Apache License 2.0",
"lines": 114,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/memzero/search.py | import json
import os
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from dotenv import load_dotenv
from jinja2 import Template
from openai import OpenAI
from prompts import ANSWER_PROMPT, ANSWER_PROMPT_GRAPH
from tqdm import tqdm
from mem0 import MemoryClient
load_dotenv()
class MemorySearch:
def __init__(self, output_path="results.json", top_k=10, filter_memories=False, is_graph=False):
self.mem0_client = MemoryClient(
api_key=os.getenv("MEM0_API_KEY"),
org_id=os.getenv("MEM0_ORGANIZATION_ID"),
project_id=os.getenv("MEM0_PROJECT_ID"),
)
self.top_k = top_k
self.openai_client = OpenAI()
self.results = defaultdict(list)
self.output_path = output_path
self.filter_memories = filter_memories
self.is_graph = is_graph
if self.is_graph:
self.ANSWER_PROMPT = ANSWER_PROMPT_GRAPH
else:
self.ANSWER_PROMPT = ANSWER_PROMPT
def search_memory(self, user_id, query, max_retries=3, retry_delay=1):
start_time = time.time()
retries = 0
while retries < max_retries:
try:
if self.is_graph:
print("Searching with graph")
memories = self.mem0_client.search(
query,
user_id=user_id,
top_k=self.top_k,
filter_memories=self.filter_memories,
enable_graph=True,
output_format="v1.1",
)
else:
memories = self.mem0_client.search(
query, user_id=user_id, top_k=self.top_k, filter_memories=self.filter_memories
)
break
except Exception as e:
print("Retrying...")
retries += 1
if retries >= max_retries:
raise e
time.sleep(retry_delay)
end_time = time.time()
if not self.is_graph:
semantic_memories = [
{
"memory": memory["memory"],
"timestamp": memory["metadata"]["timestamp"],
"score": round(memory["score"], 2),
}
for memory in memories
]
graph_memories = None
else:
semantic_memories = [
{
"memory": memory["memory"],
"timestamp": memory["metadata"]["timestamp"],
"score": round(memory["score"], 2),
}
for memory in memories["results"]
]
graph_memories = [
{"source": relation["source"], "relationship": relation["relationship"], "target": relation["target"]}
for relation in memories["relations"]
]
return semantic_memories, graph_memories, end_time - start_time
def answer_question(self, speaker_1_user_id, speaker_2_user_id, question, answer, category):
speaker_1_memories, speaker_1_graph_memories, speaker_1_memory_time = self.search_memory(
speaker_1_user_id, question
)
speaker_2_memories, speaker_2_graph_memories, speaker_2_memory_time = self.search_memory(
speaker_2_user_id, question
)
search_1_memory = [f"{item['timestamp']}: {item['memory']}" for item in speaker_1_memories]
search_2_memory = [f"{item['timestamp']}: {item['memory']}" for item in speaker_2_memories]
template = Template(self.ANSWER_PROMPT)
answer_prompt = template.render(
speaker_1_user_id=speaker_1_user_id.split("_")[0],
speaker_2_user_id=speaker_2_user_id.split("_")[0],
speaker_1_memories=json.dumps(search_1_memory, indent=4),
speaker_2_memories=json.dumps(search_2_memory, indent=4),
speaker_1_graph_memories=json.dumps(speaker_1_graph_memories, indent=4),
speaker_2_graph_memories=json.dumps(speaker_2_graph_memories, indent=4),
question=question,
)
t1 = time.time()
response = self.openai_client.chat.completions.create(
model=os.getenv("MODEL"), messages=[{"role": "system", "content": answer_prompt}], temperature=0.0
)
t2 = time.time()
response_time = t2 - t1
return (
response.choices[0].message.content,
speaker_1_memories,
speaker_2_memories,
speaker_1_memory_time,
speaker_2_memory_time,
speaker_1_graph_memories,
speaker_2_graph_memories,
response_time,
)
def process_question(self, val, speaker_a_user_id, speaker_b_user_id):
question = val.get("question", "")
answer = val.get("answer", "")
category = val.get("category", -1)
evidence = val.get("evidence", [])
adversarial_answer = val.get("adversarial_answer", "")
(
response,
speaker_1_memories,
speaker_2_memories,
speaker_1_memory_time,
speaker_2_memory_time,
speaker_1_graph_memories,
speaker_2_graph_memories,
response_time,
) = self.answer_question(speaker_a_user_id, speaker_b_user_id, question, answer, category)
result = {
"question": question,
"answer": answer,
"category": category,
"evidence": evidence,
"response": response,
"adversarial_answer": adversarial_answer,
"speaker_1_memories": speaker_1_memories,
"speaker_2_memories": speaker_2_memories,
"num_speaker_1_memories": len(speaker_1_memories),
"num_speaker_2_memories": len(speaker_2_memories),
"speaker_1_memory_time": speaker_1_memory_time,
"speaker_2_memory_time": speaker_2_memory_time,
"speaker_1_graph_memories": speaker_1_graph_memories,
"speaker_2_graph_memories": speaker_2_graph_memories,
"response_time": response_time,
}
# Save results after each question is processed
with open(self.output_path, "w") as f:
json.dump(self.results, f, indent=4)
return result
def process_data_file(self, file_path):
with open(file_path, "r") as f:
data = json.load(f)
for idx, item in tqdm(enumerate(data), total=len(data), desc="Processing conversations"):
qa = item["qa"]
conversation = item["conversation"]
speaker_a = conversation["speaker_a"]
speaker_b = conversation["speaker_b"]
speaker_a_user_id = f"{speaker_a}_{idx}"
speaker_b_user_id = f"{speaker_b}_{idx}"
for question_item in tqdm(
qa, total=len(qa), desc=f"Processing questions for conversation {idx}", leave=False
):
result = self.process_question(question_item, speaker_a_user_id, speaker_b_user_id)
self.results[idx].append(result)
# Save results after each question is processed
with open(self.output_path, "w") as f:
json.dump(self.results, f, indent=4)
# Final save at the end
with open(self.output_path, "w") as f:
json.dump(self.results, f, indent=4)
def process_questions_parallel(self, qa_list, speaker_a_user_id, speaker_b_user_id, max_workers=1):
def process_single_question(val):
result = self.process_question(val, speaker_a_user_id, speaker_b_user_id)
# Save results after each question is processed
with open(self.output_path, "w") as f:
json.dump(self.results, f, indent=4)
return result
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = list(
tqdm(executor.map(process_single_question, qa_list), total=len(qa_list), desc="Answering Questions")
)
# Final save at the end
with open(self.output_path, "w") as f:
json.dump(self.results, f, indent=4)
return results
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/memzero/search.py",
"license": "Apache License 2.0",
"lines": 188,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/openai/predict.py | import argparse
import json
import os
import time
from collections import defaultdict
from dotenv import load_dotenv
from jinja2 import Template
from openai import OpenAI
from tqdm import tqdm
load_dotenv()
ANSWER_PROMPT = """
You are an intelligent memory assistant tasked with retrieving accurate information from conversation memories.
# CONTEXT:
You have access to memories from a conversation. These memories contain
timestamped information that may be relevant to answering the question.
# INSTRUCTIONS:
1. Carefully analyze all provided memories
2. Pay special attention to the timestamps to determine the answer
3. If the question asks about a specific event or fact, look for direct evidence in the memories
4. If the memories contain contradictory information, prioritize the most recent memory
5. If there is a question about time references (like "last year", "two months ago", etc.),
calculate the actual date based on the memory timestamp. For example, if a memory from
4 May 2022 mentions "went to India last year," then the trip occurred in 2021.
6. Always convert relative time references to specific dates, months, or years. For example,
convert "last year" to "2022" or "two months ago" to "March 2023" based on the memory
timestamp. Ignore the reference while answering the question.
7. Focus only on the content of the memories. Do not confuse character
names mentioned in memories with the actual users who created those memories.
8. The answer should be less than 5-6 words.
# APPROACH (Think step by step):
1. First, examine all memories that contain information related to the question
2. Examine the timestamps and content of these memories carefully
3. Look for explicit mentions of dates, times, locations, or events that answer the question
4. If the answer requires calculation (e.g., converting relative time references), show your work
5. Formulate a precise, concise answer based solely on the evidence in the memories
6. Double-check that your answer directly addresses the question asked
7. Ensure your final answer is specific and avoids vague time references
Memories:
{{memories}}
Question: {{question}}
Answer:
"""
class OpenAIPredict:
def __init__(self, model="gpt-4o-mini"):
self.model = model
self.openai_client = OpenAI()
self.results = defaultdict(list)
def search_memory(self, idx):
with open(f"memories/{idx}.txt", "r") as file:
memories = file.read()
return memories, 0
def process_question(self, val, idx):
question = val.get("question", "")
answer = val.get("answer", "")
category = val.get("category", -1)
evidence = val.get("evidence", [])
adversarial_answer = val.get("adversarial_answer", "")
response, search_memory_time, response_time, context = self.answer_question(idx, question)
result = {
"question": question,
"answer": answer,
"category": category,
"evidence": evidence,
"response": response,
"adversarial_answer": adversarial_answer,
"search_memory_time": search_memory_time,
"response_time": response_time,
"context": context,
}
return result
def answer_question(self, idx, question):
memories, search_memory_time = self.search_memory(idx)
template = Template(ANSWER_PROMPT)
answer_prompt = template.render(memories=memories, question=question)
t1 = time.time()
response = self.openai_client.chat.completions.create(
model=os.getenv("MODEL"), messages=[{"role": "system", "content": answer_prompt}], temperature=0.0
)
t2 = time.time()
response_time = t2 - t1
return response.choices[0].message.content, search_memory_time, response_time, memories
def process_data_file(self, file_path, output_file_path):
with open(file_path, "r") as f:
data = json.load(f)
for idx, item in tqdm(enumerate(data), total=len(data), desc="Processing conversations"):
qa = item["qa"]
for question_item in tqdm(
qa, total=len(qa), desc=f"Processing questions for conversation {idx}", leave=False
):
result = self.process_question(question_item, idx)
self.results[idx].append(result)
# Save results after each question is processed
with open(output_file_path, "w") as f:
json.dump(self.results, f, indent=4)
# Final save at the end
with open(output_file_path, "w") as f:
json.dump(self.results, f, indent=4)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output_file_path", type=str, required=True)
args = parser.parse_args()
openai_predict = OpenAIPredict()
openai_predict.process_data_file("../../dataset/locomo10.json", args.output_file_path)
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/openai/predict.py",
"license": "Apache License 2.0",
"lines": 103,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/rag.py | import json
import os
import time
from collections import defaultdict
import numpy as np
import tiktoken
from dotenv import load_dotenv
from jinja2 import Template
from openai import OpenAI
from tqdm import tqdm
load_dotenv()
PROMPT = """
# Question:
{{QUESTION}}
# Context:
{{CONTEXT}}
# Short answer:
"""
class RAGManager:
def __init__(self, data_path="dataset/locomo10_rag.json", chunk_size=500, k=1):
self.model = os.getenv("MODEL")
self.client = OpenAI()
self.data_path = data_path
self.chunk_size = chunk_size
self.k = k
def generate_response(self, question, context):
template = Template(PROMPT)
prompt = template.render(CONTEXT=context, QUESTION=question)
max_retries = 3
retries = 0
while retries <= max_retries:
try:
t1 = time.time()
response = self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": "You are a helpful assistant that can answer "
"questions based on the provided context."
"If the question involves timing, use the conversation date for reference."
"Provide the shortest possible answer."
"Use words directly from the conversation when possible."
"Avoid using subjects in your answer.",
},
{"role": "user", "content": prompt},
],
temperature=0,
)
t2 = time.time()
return response.choices[0].message.content.strip(), t2 - t1
except Exception as e:
retries += 1
if retries > max_retries:
raise e
time.sleep(1) # Wait before retrying
def clean_chat_history(self, chat_history):
cleaned_chat_history = ""
for c in chat_history:
cleaned_chat_history += f"{c['timestamp']} | {c['speaker']}: {c['text']}\n"
return cleaned_chat_history
def calculate_embedding(self, document):
response = self.client.embeddings.create(model=os.getenv("EMBEDDING_MODEL"), input=document)
return response.data[0].embedding
def calculate_similarity(self, embedding1, embedding2):
return np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))
def search(self, query, chunks, embeddings, k=1):
"""
Search for the top-k most similar chunks to the query.
Args:
query: The query string
chunks: List of text chunks
embeddings: List of embeddings for each chunk
k: Number of top chunks to return (default: 1)
Returns:
combined_chunks: The combined text of the top-k chunks
search_time: Time taken for the search
"""
t1 = time.time()
query_embedding = self.calculate_embedding(query)
similarities = [self.calculate_similarity(query_embedding, embedding) for embedding in embeddings]
# Get indices of top-k most similar chunks
if k == 1:
# Original behavior - just get the most similar chunk
top_indices = [np.argmax(similarities)]
else:
# Get indices of top-k chunks
top_indices = np.argsort(similarities)[-k:][::-1]
# Combine the top-k chunks
combined_chunks = "\n<->\n".join([chunks[i] for i in top_indices])
t2 = time.time()
return combined_chunks, t2 - t1
def create_chunks(self, chat_history, chunk_size=500):
"""
Create chunks using tiktoken for more accurate token counting
"""
# Get the encoding for the model
encoding = tiktoken.encoding_for_model(os.getenv("EMBEDDING_MODEL"))
documents = self.clean_chat_history(chat_history)
if chunk_size == -1:
return [documents], []
chunks = []
# Encode the document
tokens = encoding.encode(documents)
# Split into chunks based on token count
for i in range(0, len(tokens), chunk_size):
chunk_tokens = tokens[i : i + chunk_size]
chunk = encoding.decode(chunk_tokens)
chunks.append(chunk)
embeddings = []
for chunk in chunks:
embedding = self.calculate_embedding(chunk)
embeddings.append(embedding)
return chunks, embeddings
def process_all_conversations(self, output_file_path):
with open(self.data_path, "r") as f:
data = json.load(f)
FINAL_RESULTS = defaultdict(list)
for key, value in tqdm(data.items(), desc="Processing conversations"):
chat_history = value["conversation"]
questions = value["question"]
chunks, embeddings = self.create_chunks(chat_history, self.chunk_size)
for item in tqdm(questions, desc="Answering questions", leave=False):
question = item["question"]
answer = item.get("answer", "")
category = item["category"]
if self.chunk_size == -1:
context = chunks[0]
search_time = 0
else:
context, search_time = self.search(question, chunks, embeddings, k=self.k)
response, response_time = self.generate_response(question, context)
FINAL_RESULTS[key].append(
{
"question": question,
"answer": answer,
"category": category,
"context": context,
"response": response,
"search_time": search_time,
"response_time": response_time,
}
)
with open(output_file_path, "w+") as f:
json.dump(FINAL_RESULTS, f, indent=4)
# Save results
with open(output_file_path, "w+") as f:
json.dump(FINAL_RESULTS, f, indent=4)
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/rag.py",
"license": "Apache License 2.0",
"lines": 148,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/zep/add.py | import argparse
import json
import os
from dotenv import load_dotenv
from tqdm import tqdm
from zep_cloud import Message
from zep_cloud.client import Zep
load_dotenv()
class ZepAdd:
def __init__(self, data_path=None):
self.zep_client = Zep(api_key=os.getenv("ZEP_API_KEY"))
self.data_path = data_path
self.data = None
if data_path:
self.load_data()
def load_data(self):
with open(self.data_path, "r") as f:
self.data = json.load(f)
return self.data
def process_conversation(self, run_id, item, idx):
conversation = item["conversation"]
user_id = f"run_id_{run_id}_experiment_user_{idx}"
session_id = f"run_id_{run_id}_experiment_session_{idx}"
# # delete all memories for the two users
# self.zep_client.user.delete(user_id=user_id)
# self.zep_client.memory.delete(session_id=session_id)
self.zep_client.user.add(user_id=user_id)
self.zep_client.memory.add_session(
user_id=user_id,
session_id=session_id,
)
print("Starting to add memories... for user", user_id)
for key in tqdm(conversation.keys(), desc=f"Processing user {user_id}"):
if key in ["speaker_a", "speaker_b"] or "date" in key:
continue
date_time_key = key + "_date_time"
timestamp = conversation[date_time_key]
chats = conversation[key]
for chat in tqdm(chats, desc=f"Adding chats for {key}", leave=False):
self.zep_client.memory.add(
session_id=session_id,
messages=[
Message(
role=chat["speaker"],
role_type="user",
content=f"{timestamp}: {chat['text']}",
)
],
)
def process_all_conversations(self, run_id):
if not self.data:
raise ValueError("No data loaded. Please set data_path and call load_data() first.")
for idx, item in tqdm(enumerate(self.data)):
if idx == 0:
self.process_conversation(run_id, item, idx)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--run_id", type=str, required=True)
args = parser.parse_args()
zep_add = ZepAdd(data_path="../../dataset/locomo10.json")
zep_add.process_all_conversations(args.run_id)
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/zep/add.py",
"license": "Apache License 2.0",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
mem0ai/mem0:evaluation/src/zep/search.py | import argparse
import json
import os
import time
from collections import defaultdict
from dotenv import load_dotenv
from jinja2 import Template
from openai import OpenAI
from prompts import ANSWER_PROMPT_ZEP
from tqdm import tqdm
from zep_cloud import EntityEdge, EntityNode
from zep_cloud.client import Zep
load_dotenv()
TEMPLATE = """
FACTS and ENTITIES represent relevant context to the current conversation.
# These are the most relevant facts and their valid date ranges
# format: FACT (Date range: from - to)
{facts}
# These are the most relevant entities
# ENTITY_NAME: entity summary
{entities}
"""
class ZepSearch:
def __init__(self):
self.zep_client = Zep(api_key=os.getenv("ZEP_API_KEY"))
self.results = defaultdict(list)
self.openai_client = OpenAI()
def format_edge_date_range(self, edge: EntityEdge) -> str:
# return f"{datetime(edge.valid_at).strftime('%Y-%m-%d %H:%M:%S') if edge.valid_at else 'date unknown'} - {(edge.invalid_at.strftime('%Y-%m-%d %H:%M:%S') if edge.invalid_at else 'present')}"
return f"{edge.valid_at if edge.valid_at else 'date unknown'} - {(edge.invalid_at if edge.invalid_at else 'present')}"
def compose_search_context(self, edges: list[EntityEdge], nodes: list[EntityNode]) -> str:
facts = [f" - {edge.fact} ({self.format_edge_date_range(edge)})" for edge in edges]
entities = [f" - {node.name}: {node.summary}" for node in nodes]
return TEMPLATE.format(facts="\n".join(facts), entities="\n".join(entities))
def search_memory(self, run_id, idx, query, max_retries=3, retry_delay=1):
start_time = time.time()
retries = 0
while retries < max_retries:
try:
user_id = f"run_id_{run_id}_experiment_user_{idx}"
edges_results = (
self.zep_client.graph.search(
user_id=user_id, reranker="cross_encoder", query=query, scope="edges", limit=20
)
).edges
node_results = (
self.zep_client.graph.search(user_id=user_id, reranker="rrf", query=query, scope="nodes", limit=20)
).nodes
context = self.compose_search_context(edges_results, node_results)
break
except Exception as e:
print("Retrying...")
retries += 1
if retries >= max_retries:
raise e
time.sleep(retry_delay)
end_time = time.time()
return context, end_time - start_time
def process_question(self, run_id, val, idx):
question = val.get("question", "")
answer = val.get("answer", "")
category = val.get("category", -1)
evidence = val.get("evidence", [])
adversarial_answer = val.get("adversarial_answer", "")
response, search_memory_time, response_time, context = self.answer_question(run_id, idx, question)
result = {
"question": question,
"answer": answer,
"category": category,
"evidence": evidence,
"response": response,
"adversarial_answer": adversarial_answer,
"search_memory_time": search_memory_time,
"response_time": response_time,
"context": context,
}
return result
def answer_question(self, run_id, idx, question):
context, search_memory_time = self.search_memory(run_id, idx, question)
template = Template(ANSWER_PROMPT_ZEP)
answer_prompt = template.render(memories=context, question=question)
t1 = time.time()
response = self.openai_client.chat.completions.create(
model=os.getenv("MODEL"), messages=[{"role": "system", "content": answer_prompt}], temperature=0.0
)
t2 = time.time()
response_time = t2 - t1
return response.choices[0].message.content, search_memory_time, response_time, context
def process_data_file(self, file_path, run_id, output_file_path):
with open(file_path, "r") as f:
data = json.load(f)
for idx, item in tqdm(enumerate(data), total=len(data), desc="Processing conversations"):
qa = item["qa"]
for question_item in tqdm(
qa, total=len(qa), desc=f"Processing questions for conversation {idx}", leave=False
):
result = self.process_question(run_id, question_item, idx)
self.results[idx].append(result)
# Save results after each question is processed
with open(output_file_path, "w") as f:
json.dump(self.results, f, indent=4)
# Final save at the end
with open(output_file_path, "w") as f:
json.dump(self.results, f, indent=4)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--run_id", type=str, required=True)
args = parser.parse_args()
zep_search = ZepSearch()
zep_search.process_data_file("../../dataset/locomo10.json", args.run_id, "results/zep_search_results.json")
| {
"repo_id": "mem0ai/mem0",
"file_path": "evaluation/src/zep/search.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/BitNet:utils/quantize_embeddings.py | #!/usr/bin/env python3
"""
Embedding Quantization Script
This script converts ggml-model-f32.gguf to multiple quantized versions
with different token embedding types.
"""
import subprocess
import os
import argparse
import re
import csv
from pathlib import Path
from datetime import datetime
class EmbeddingQuantizer:
def __init__(self, input_model, output_dir, quantize_bin="../build/bin/llama-quantize",
bench_bin="../build/bin/llama-bench", stats_dir="../stats", csv_output=None):
self.input_model = Path(input_model)
self.output_dir = Path(output_dir)
self.quantize_bin = Path(quantize_bin)
self.bench_bin = Path(bench_bin)
self.stats_dir = Path(stats_dir)
self.csv_output = Path(csv_output) if csv_output else None
# Verify input file exists
if not self.input_model.exists():
raise FileNotFoundError(f"Input model not found: {self.input_model}")
# Verify quantize tool exists
if not self.quantize_bin.exists():
raise FileNotFoundError(f"Quantize binary not found: {self.quantize_bin}")
# Verify bench tool exists
if not self.bench_bin.exists():
raise FileNotFoundError(f"Benchmark binary not found: {self.bench_bin}")
# Create output directories
self.output_dir.mkdir(parents=True, exist_ok=True)
self.stats_dir.mkdir(parents=True, exist_ok=True)
self.results = []
self.newly_created_files = set() # Track newly created files
def quantize(self, embedding_type, output_suffix):
"""
Perform single quantization
Args:
embedding_type: Token embedding type (uppercase format, e.g., Q6_K)
output_suffix: Output file suffix (lowercase format, e.g., q6_k)
Returns:
bool: Whether successful
"""
output_file = self.output_dir / f"ggml-model-i2_s-embed-{output_suffix}.gguf"
# Check if file already exists
file_already_existed = output_file.exists()
if file_already_existed:
print(f"ℹ️ File already exists: {output_file}")
print(f" Skipping quantization, will use existing file for benchmark")
return True
cmd = [
str(self.quantize_bin),
"--token-embedding-type", embedding_type,
str(self.input_model),
str(output_file),
"I2_S",
"1",
"1"
]
print(f"\n{'='*80}")
print(f"🔄 Quantizing with embedding type: {embedding_type}")
print(f"📥 Input: {self.input_model}")
print(f"📤 Output: {output_file}")
print(f"💻 Command: {' '.join(cmd)}")
print(f"{'='*80}\n")
start_time = datetime.now()
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=os.getcwd(),
timeout=600 # 10 minute timeout
)
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
if result.returncode == 0:
# Get output file size
file_size_mb = output_file.stat().st_size / (1024 * 1024)
print(f"✅ Success! Duration: {duration:.2f}s, Size: {file_size_mb:.2f} MB")
# Record newly created file
if not file_already_existed:
self.newly_created_files.add(output_file)
# Print part of output
if result.stdout:
print("\n📊 Quantization output:")
print(result.stdout[-500:] if len(result.stdout) > 500 else result.stdout)
return True
else:
print(f"❌ Failed with return code {result.returncode}")
print(f"Error: {result.stderr}")
return False
except subprocess.TimeoutExpired:
print(f"❌ Timeout (exceeded 10 minutes)")
return False
except Exception as e:
print(f"❌ Exception: {e}")
return False
def benchmark_model(self, output_suffix):
"""
Benchmark model
Args:
output_suffix: Output file suffix (lowercase format, e.g., q6_k)
Returns:
dict: Dictionary with benchmark results, or None if failed
"""
model_file = self.output_dir / f"ggml-model-i2_s-embed-{output_suffix}.gguf"
if not model_file.exists():
print(f"❌ Model file not found for benchmarking: {model_file}")
return None
cmd = [
str(self.bench_bin),
"-m", str(model_file),
"-p", "128",
"-n", "0",
"-t", "1,2,4,8",
"-ngl", "0"
]
print(f"\n{'='*80}")
print(f"🏃 Running benchmark for: {output_suffix}")
print(f"💻 Command: {' '.join(cmd)}")
print(f"{'='*80}\n")
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=os.getcwd(),
timeout=300 # 5 minute timeout
)
if result.returncode == 0:
print("✅ Benchmark completed successfully")
print("\n📊 Benchmark output:")
print(result.stdout)
# 解析输出
bench_results = self.parse_benchmark_output(result.stdout, output_suffix)
return bench_results
else:
print(f"❌ Benchmark failed with return code {result.returncode}")
print(f"Error: {result.stderr}")
return None
except subprocess.TimeoutExpired:
print(f"❌ Benchmark timeout (exceeded 5 minutes)")
return None
except Exception as e:
print(f"❌ Benchmark exception: {e}")
return None
def parse_benchmark_output(self, output, output_suffix):
"""
Parse benchmark output to extract t/s data (mean±std)
Args:
output: Benchmark command output
output_suffix: Output file suffix
Returns:
dict: Dictionary with parsed results
"""
results = {
'embedding_type': output_suffix,
'threads_1': None,
'threads_2': None,
'threads_4': None,
'threads_8': None,
}
# Parse table data
# Find lines containing pp128 and t/s
lines = output.strip().split('\n')
for line in lines:
# Skip header and separator lines
if '|' not in line or 'model' in line or '---' in line:
continue
# Try to extract data
# Format similar to: | bitnet-25 2B I2_S - 2 bpw ternary | 1012.28 MiB | 2.74 B | CPU | 12 | pp128 | 405.73 ± 3.69 |
parts = [p.strip() for p in line.split('|')]
if len(parts) >= 8 and 'pp128' in parts[6]:
threads_str = parts[5].strip()
throughput_str = parts[7].strip()
# Extract thread count
try:
threads = int(threads_str)
except:
continue
# Extract t/s data (format: "405.73 ± 3.69" or "405.73")
# Try to match "mean ± std" format
match_with_std = re.search(r'([\d.]+)\s*±\s*([\d.]+)', throughput_str)
if match_with_std:
mean = float(match_with_std.group(1))
std = float(match_with_std.group(2))
throughput = f"{mean:.2f}±{std:.2f}"
else:
# Only mean, no std
match = re.search(r'([\d.]+)', throughput_str)
if match:
throughput = f"{float(match.group(1)):.2f}"
else:
continue
# Store result based on thread count
if threads == 1:
results['threads_1'] = throughput
elif threads == 2:
results['threads_2'] = throughput
elif threads == 4:
results['threads_4'] = throughput
elif threads == 8:
results['threads_8'] = throughput
return results
def cleanup_model(self, output_suffix):
"""
Cleanup model files (only delete newly created files)
Args:
output_suffix: Output file suffix
"""
model_file = self.output_dir / f"ggml-model-i2_s-embed-{output_suffix}.gguf"
if model_file in self.newly_created_files:
try:
model_file.unlink()
print(f"🗑️ Deleted newly created file: {model_file}")
self.newly_created_files.remove(model_file)
except Exception as e:
print(f"⚠️ Failed to delete {model_file}: {e}")
else:
print(f"ℹ️ Keeping existing file: {model_file}")
def run_all_quantizations(self, types_to_quantize):
"""
Run all quantizations
Args:
types_to_quantize: List of quantization types, tuples of (embedding_type, output_suffix)
"""
print(f"\n{'='*80}")
print(f"🚀 Starting Embedding Quantization and Benchmarking")
print(f"{'='*80}")
print(f"📥 Input model: {self.input_model}")
print(f"📤 Output directory: {self.output_dir}")
print(f"📊 Stats directory: {self.stats_dir}")
print(f"🔢 Total quantizations: {len(types_to_quantize)}")
print(f"{'='*80}\n")
total_start = datetime.now()
for i, (embedding_type, output_suffix) in enumerate(types_to_quantize, 1):
print(f"\n{'#'*80}")
print(f"[{i}/{len(types_to_quantize)}] Processing {output_suffix} ({embedding_type})")
print(f"{'#'*80}\n")
# Quantize model
success = self.quantize(embedding_type, output_suffix)
if not success:
print(f"⚠️ Skipping benchmark for {output_suffix} due to quantization failure")
continue
# Run benchmark
bench_results = self.benchmark_model(output_suffix)
if bench_results:
self.results.append(bench_results)
else:
print(f"⚠️ Benchmark failed for {output_suffix}")
# Cleanup model files (only delete newly created files)
self.cleanup_model(output_suffix)
print(f"\n{'#'*80}")
print(f"✅ Completed {output_suffix}")
print(f"{'#'*80}\n")
total_end = datetime.now()
total_duration = (total_end - total_start).total_seconds()
# 保存结果到CSV
self.save_results_to_csv()
# 打印总结
self.print_summary(total_duration)
def save_results_to_csv(self):
"""将benchmark结果保存到CSV文件"""
if not self.results:
print("⚠️ No results to save")
return
# Use user-specified CSV path, otherwise use default path
if self.csv_output:
csv_file = self.csv_output
# Ensure parent directory exists
csv_file.parent.mkdir(parents=True, exist_ok=True)
else:
csv_file = self.stats_dir / f"embedding_benchmark.csv"
print(f"\n💾 Saving results to: {csv_file}")
try:
with open(csv_file, 'w', newline='') as f:
fieldnames = ['embedding_type', 'threads_1', 'threads_2', 'threads_4', 'threads_8']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for result in self.results:
writer.writerow(result)
print(f"✅ Results saved successfully")
# Also print table
print(f"\n📊 Benchmark Results:")
print(f"{'Type':<15} {'1 thread':<18} {'2 threads':<18} {'4 threads':<18} {'8 threads':<18}")
print("-" * 87)
for result in self.results:
t1 = result['threads_1'] if result['threads_1'] else "N/A"
t2 = result['threads_2'] if result['threads_2'] else "N/A"
t4 = result['threads_4'] if result['threads_4'] else "N/A"
t8 = result['threads_8'] if result['threads_8'] else "N/A"
print(f"{result['embedding_type']:<15} {t1:<18} {t2:<18} {t4:<18} {t8:<18}")
except Exception as e:
print(f"❌ Failed to save results: {e}")
def print_summary(self, total_duration):
"""Print quantization summary"""
print(f"\n\n{'='*80}")
print(f"📊 QUANTIZATION AND BENCHMARK SUMMARY")
print(f"{'='*80}\n")
successful = len(self.results)
total = len(self.results)
print(f"✅ Completed: {successful} benchmarks")
print(f"⏱️ Total duration: {total_duration/60:.2f} minutes\n")
if self.results:
if self.csv_output and self.csv_output.exists():
print(f"📁 Results saved to: {self.csv_output}")
else:
csv_files = list(self.stats_dir.glob("embedding_benchmark*.csv"))
if csv_files:
latest_csv = max(csv_files, key=lambda p: p.stat().st_mtime)
print(f"📁 Results saved to: {latest_csv}")
print(f"\n{'='*80}\n")
def main():
parser = argparse.ArgumentParser(description='Quantize model embeddings to multiple formats')
parser.add_argument('--input', '-i',
default='../models/BitNet-b1.58-2B-4T/ggml-model-f32.gguf',
help='Input model path (default: ../models/BitNet-b1.58-2B-4T/ggml-model-f32.gguf)')
parser.add_argument('--output-dir', '-o',
default='../models/BitNet-b1.58-2B-4T',
help='Output directory (default: ../models/BitNet-b1.58-2B-4T)')
parser.add_argument('--quantize-bin', '-q',
default='../build/bin/llama-quantize',
help='Path to llama-quantize binary (default: ../build/bin/llama-quantize)')
parser.add_argument('--bench-bin', '-b',
default='../build/bin/llama-bench',
help='Path to llama-bench binary (default: ../build/bin/llama-bench)')
parser.add_argument('--stats-dir',
default='../stats',
help='Directory to save benchmark results (default: ../stats)')
parser.add_argument('--csv-output', '-c',
help='Custom path for CSV output file (e.g., stats/my_results.csv)')
parser.add_argument('--types', '-t',
nargs='+',
help='Specific types to quantize (e.g., f32 q6_k q4_0)')
parser.add_argument('--skip-existing', '-s',
action='store_true',
help='Skip quantization if output file already exists (will still benchmark existing files)')
args = parser.parse_args()
# Define all supported quantization types
# Format: (embedding_type for command line, output_suffix for filename)
all_types = [
('F32', 'f32'),
('F16', 'f16'),
('Q8_0', 'q8_0'),
('Q6_K', 'q6_k'),
('Q5_0', 'q5_0'),
('Q4_0', 'q4_0'),
('Q3_K', 'q3_k'),
('TQ2_0', 'tq2_0'),
]
# If specific types are specified, filter the list
if args.types:
types_lower = [t.lower() for t in args.types]
types_to_quantize = [(et, os) for et, os in all_types if os.lower() in types_lower]
if not types_to_quantize:
print(f"❌ No valid types specified. Available types: {', '.join([os for _, os in all_types])}")
return
else:
types_to_quantize = all_types
# If skip existing files is enabled, no need to filter
# Because new logic will automatically detect and skip during quantization, but will still benchmark
# 创建量化器并运行
try:
quantizer = EmbeddingQuantizer(
args.input,
args.output_dir,
args.quantize_bin,
args.bench_bin,
args.stats_dir,
args.csv_output
)
quantizer.run_all_quantizations(types_to_quantize)
except FileNotFoundError as e:
print(f"❌ Error: {e}")
return 1
except KeyboardInterrupt:
print("\n\n⚠️ Quantization interrupted by user")
return 1
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
exit(main() or 0)
| {
"repo_id": "microsoft/BitNet",
"file_path": "utils/quantize_embeddings.py",
"license": "MIT License",
"lines": 388,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/BitNet:utils/tune_gemm_config.py | #!/usr/bin/env python3
"""
GEMM Configuration Tuning Script
This script automatically tunes ROW_BLOCK_SIZE, COL_BLOCK_SIZE, and PARALLEL_SIZE
to find the optimal configuration for maximum throughput (t/s).
"""
import subprocess
import os
import re
import csv
import shutil
from datetime import datetime
from pathlib import Path
import argparse
class GemmTuner:
def __init__(self, config_path, model_path, threads=16):
self.config_path = Path(config_path)
self.model_path = model_path
self.threads = threads
self.backup_path = self.config_path.parent / f"gemm-config.h.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
self.build_dir = Path("../build")
self.results = []
def backup_config(self):
"""Backup current configuration file"""
print(f"📦 Backing up current config to {self.backup_path}")
shutil.copy2(self.config_path, self.backup_path)
def restore_config(self):
"""Restore original configuration file"""
print(f"♻️ Restoring original config from {self.backup_path}")
shutil.copy2(self.backup_path, self.config_path)
def generate_config(self, act_parallel, row_block_size, col_block_size, parallel_size):
"""Generate new configuration file with simplified format"""
content = ""
# Simplified configuration format
if act_parallel:
content += "#define ACT_PARALLEL\n"
content += f"#define ROW_BLOCK_SIZE {row_block_size}\n"
content += f"#define COL_BLOCK_SIZE {col_block_size}\n"
content += f"#define PARALLEL_SIZE {parallel_size}\n"
with open(self.config_path, 'w') as f:
f.write(content)
def rebuild_project(self):
"""Rebuild project"""
print("🔨 Rebuilding project...")
result = subprocess.run(
["cmake", "--build", str(self.build_dir), "--target", "llama-bench"],
capture_output=True,
text=True,
cwd=os.getcwd()
)
if result.returncode != 0:
print(f"⚠️ Build warning/error: {result.stderr}")
return False
return True
def run_benchmark(self):
"""Run benchmark test"""
cmd = [
f"{self.build_dir}/bin/llama-bench",
"-m", self.model_path,
"-p", "128",
"-n", "0",
"-t", str(self.threads),
"-ngl", "0"
]
print(f"⚡ Running benchmark: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=os.getcwd(),
timeout=300 # 5分钟超时
)
if result.returncode != 0:
print(f"❌ Benchmark failed: {result.stderr}")
return None
return result.stdout
def parse_throughput(self, output):
"""Parse pp128 throughput from output"""
# 匹配 pp128: | pp128 | 501.06 ± 11.37 |
pp_pattern = r'\|\s+pp128\s+\|\s+([\d.]+)\s+±\s+([\d.]+)\s+\|'
pp_match = re.search(pp_pattern, output)
if pp_match:
pp_throughput = float(pp_match.group(1))
pp_std_dev = float(pp_match.group(2))
return {
'pp_throughput': pp_throughput,
'pp_std_dev': pp_std_dev
}
return None
def test_configuration(self, act_parallel, row_block_size, col_block_size, parallel_size):
"""Test single configuration"""
config_name = f"ACT_{'ON' if act_parallel else 'OFF'}_R{row_block_size}_C{col_block_size}_P{parallel_size}"
print(f"\n{'='*80}")
print(f"🧪 Testing configuration: {config_name}")
print(f" ACT_PARALLEL: {act_parallel}")
print(f" ROW_BLOCK_SIZE: {row_block_size}")
print(f" COL_BLOCK_SIZE: {col_block_size}")
print(f" PARALLEL_SIZE: {parallel_size}")
print(f"{'='*80}")
# Generate configuration
self.generate_config(act_parallel, row_block_size, col_block_size, parallel_size)
# Rebuild project
if not self.rebuild_project():
print("⚠️ Build failed, skipping this configuration")
return None
# Run benchmark test
output = self.run_benchmark()
if output is None:
return None
# Parse results
metrics = self.parse_throughput(output)
if metrics is not None:
result = {
'act_parallel': act_parallel,
'row_block_size': row_block_size,
'col_block_size': col_block_size,
'parallel_size': parallel_size,
'config_name': config_name,
**metrics
}
self.results.append(result)
print(f"✅ PP128: {metrics['pp_throughput']:.2f} ± {metrics['pp_std_dev']:.2f} t/s")
return result
else:
print("❌ Failed to parse throughput")
return None
def save_results(self, csv_path):
"""Save results to CSV file"""
print(f"\n💾 Saving results to {csv_path}")
with open(csv_path, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=[
'config_name', 'act_parallel', 'row_block_size',
'col_block_size', 'parallel_size',
'pp_throughput', 'pp_std_dev'
])
writer.writeheader()
writer.writerows(self.results)
def find_best_config(self):
"""Find the best configuration with highest throughput"""
if not self.results:
print("❌ No valid results found")
return None
best = max(self.results, key=lambda x: x['pp_throughput'])
return best
def run_tuning(self, configurations, output_csv=None):
"""Run test for all configurations"""
print(f"\n🚀 Starting tuning process with {len(configurations)} configurations")
print(f"📊 Model: {self.model_path}")
print(f"🧵 Threads: {self.threads}\n")
# Backup configuration
self.backup_config()
try:
# Test all configurations
for i, config in enumerate(configurations, 1):
print(f"\n[{i}/{len(configurations)}]")
self.test_configuration(**config)
# Save results
if output_csv is None:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
csv_path = f"../stats/tuning_results_{timestamp}.csv"
else:
csv_path = output_csv
# Ensure stats directory exists
os.makedirs(os.path.dirname(csv_path), exist_ok=True)
self.save_results(csv_path)
# Find best configuration
best = self.find_best_config()
if best:
print(f"\n{'='*80}")
print(f"🏆 BEST CONFIGURATION FOUND!")
print(f"{'='*80}")
print(f"Configuration: {best['config_name']}")
print(f"ACT_PARALLEL: {best['act_parallel']}")
print(f"ROW_BLOCK_SIZE: {best['row_block_size']}")
print(f"COL_BLOCK_SIZE: {best['col_block_size']}")
print(f"PARALLEL_SIZE: {best['parallel_size']}")
print(f"PP128 Throughput: {best['pp_throughput']:.2f} ± {best['pp_std_dev']:.2f} t/s")
print(f"{'='*80}\n")
# Show the configuration that will be written
print("Configuration to be written to gemm-config.h:")
print("-" * 80)
if best['act_parallel']:
print("#define ACT_PARALLEL")
print(f"#define ROW_BLOCK_SIZE {best['row_block_size']}")
print(f"#define COL_BLOCK_SIZE {best['col_block_size']}")
print(f"#define PARALLEL_SIZE {best['parallel_size']}")
print("-" * 80)
# Apply best configuration
apply = input("\nDo you want to apply this configuration to gemm-config.h? (y/n): ").strip().lower()
if apply == 'y':
self.generate_config(
best['act_parallel'],
best['row_block_size'],
best['col_block_size'],
best['parallel_size']
)
self.rebuild_project()
print("✅ Best configuration applied and project rebuilt!")
else:
self.restore_config()
print("✅ Original configuration restored")
# Clean up backup file
if self.backup_path.exists():
self.backup_path.unlink()
print(f"🗑️ Removed backup file: {self.backup_path}")
except KeyboardInterrupt:
print("\n⚠️ Tuning interrupted by user")
self.restore_config()
# Clean up backup file
if self.backup_path.exists():
self.backup_path.unlink()
print(f"🗑️ Removed backup file: {self.backup_path}")
except Exception as e:
print(f"\n❌ Error during tuning: {e}")
self.restore_config()
# Clean up backup file
if self.backup_path.exists():
self.backup_path.unlink()
print(f"🗑️ Removed backup file: {self.backup_path}")
raise
def generate_configurations():
"""Generate list of configurations to test"""
configurations = []
act_parallel_options = [True]
row_sizes = [2, 4, 8]#[2, 4, 8, 16, 32]
col_sizes = [32, 64]#[32, 64, 128, 256, 512, 1024]
parallelism_degree = [4]
for act_parallel in act_parallel_options:
for row in row_sizes:
for col in col_sizes:
for parallel in parallelism_degree:
# Add filtering conditions
if act_parallel:
# When ACT_PARALLEL=True, only calculate combinations with parallel < row
if parallel > row:
continue
else:
# When ACT_PARALLEL=False, only calculate combinations with parallel < col
if parallel > col:
continue
configurations.append({
'act_parallel': act_parallel,
'row_block_size': row,
'col_block_size': col,
'parallel_size': parallel
})
return configurations
def main():
parser = argparse.ArgumentParser(description='Tune GEMM configuration for optimal performance')
parser.add_argument('--config', default='../include/gemm-config.h',
help='Path to gemm-config.h file')
parser.add_argument('--model', default='../models/BitNet-b1.58-2B-4T/ggml-model-i2_s-embed-q6_k.gguf',
help='Path to model file')
parser.add_argument('--threads', type=int, default=8,
help='Number of threads to use')
parser.add_argument('--quick', action='store_true',
help='Quick test with fewer configurations')
parser.add_argument('--custom', action='store_true',
help='Manually specify configurations to test')
parser.add_argument('--output', type=str, default=None,
help='Output CSV file path (default: stats/tuning_results_<timestamp>.csv)')
args = parser.parse_args()
tuner = GemmTuner(args.config, args.model, args.threads)
if args.custom:
# Custom configuration mode
print("Custom configuration mode")
configurations = []
while True:
print("\nEnter configuration (or 'done' to finish):")
act = input("ACT_PARALLEL (y/n): ").strip().lower() == 'y'
if input == 'done':
break
row = int(input("ROW_BLOCK_SIZE: "))
col = int(input("COL_BLOCK_SIZE: "))
par = int(input("PARALLEL_SIZE: "))
configurations.append({
'act_parallel': act,
'row_block_size': row,
'col_block_size': col,
'parallel_size': par
})
elif args.quick:
# Quick test mode - test only a few key configurations
configurations = [
{'act_parallel': True, 'row_block_size': 4, 'col_block_size': 128, 'parallel_size': 4},
{'act_parallel': True, 'row_block_size': 8, 'col_block_size': 128, 'parallel_size': 4},
{'act_parallel': True, 'row_block_size': 4, 'col_block_size': 64, 'parallel_size': 4},
{'act_parallel': False, 'row_block_size': 32, 'col_block_size': 4, 'parallel_size': 4},
{'act_parallel': False, 'row_block_size': 16, 'col_block_size': 4, 'parallel_size': 4},
]
else:
# Full test mode
configurations = generate_configurations()
print(f"\n{'='*80}")
print(f"GEMM Configuration Tuner")
print(f"{'='*80}")
print(f"Total configurations to test: {len(configurations)}")
print(f"Estimated time: ~{len(configurations) * 0.5:.1f} minutes (assuming 30s per test)")
print(f"{'='*80}\n")
proceed = input("Proceed with tuning? (y/n): ").strip().lower()
if proceed != 'y':
print("Tuning cancelled")
return
tuner.run_tuning(configurations, output_csv=args.output)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/BitNet",
"file_path": "utils/tune_gemm_config.py",
"license": "MIT License",
"lines": 306,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/BitNet:utils/convert-helper-bitnet.py | #!/usr/bin/env python3
import sys
import os
import shutil
import subprocess
from pathlib import Path
def run_command(command_list, cwd=None, check=True):
print(f"Executing: {' '.join(map(str, command_list))}")
try:
process = subprocess.run(command_list, cwd=cwd, check=check, capture_output=False, text=True)
return process
except subprocess.CalledProcessError as e:
print(f"Error executing command: {' '.join(map(str, e.cmd))}")
print(f"Return code: {e.returncode}")
raise
def main():
if len(sys.argv) < 2:
script_name = Path(sys.argv[0]).name
print(f"Usage: python {script_name} <model-directory>")
sys.exit(1)
model_dir_arg = sys.argv[1]
model_dir = Path(model_dir_arg).resolve()
if not model_dir.is_dir():
print(f"Error: Model directory '{model_dir}' not found or is not a directory.")
sys.exit(1)
utils_dir = Path(__file__).parent.resolve()
project_root_dir = utils_dir.parent
preprocess_script = utils_dir / "preprocess-huggingface-bitnet.py"
convert_script = utils_dir / "convert-ms-to-gguf-bitnet.py"
llama_quantize_binary = project_root_dir / "build" / "bin" / "llama-quantize"
input_file = model_dir / "model.safetensors"
input_backup_file = model_dir / "model.safetensors.backup"
preprocessed_output_file = model_dir / "model.safetensors"
gguf_f32_output = model_dir / "ggml-model-f32-bitnet.gguf"
gguf_i2s_output = model_dir / "ggml-model-i2s-bitnet.gguf"
if not preprocess_script.is_file():
print(f"Error: Preprocess script not found at '{preprocess_script}'")
sys.exit(1)
if not convert_script.is_file():
print(f"Error: Convert script not found at '{convert_script}'")
sys.exit(1)
if not llama_quantize_binary.is_file():
print(f"Error: llama-quantize binary not found at '{llama_quantize_binary}'")
sys.exit(1)
if not input_file.is_file():
print(f"Error: Input safetensors file not found at '{input_file}'")
sys.exit(1)
try:
print(f"Backing up '{input_file}' to '{input_backup_file}'")
if input_backup_file.exists():
print(f"Warning: Removing existing backup file '{input_backup_file}'")
input_backup_file.unlink()
shutil.move(input_file, input_backup_file)
print("Preprocessing huggingface checkpoint...")
cmd_preprocess = [
sys.executable,
str(preprocess_script),
"--input", str(input_backup_file),
"--output", str(preprocessed_output_file)
]
run_command(cmd_preprocess)
print("Converting to GGUF (f32)...")
cmd_convert = [
sys.executable,
str(convert_script),
str(model_dir),
"--vocab-type", "bpe",
"--outtype", "f32",
"--concurrency", "1",
"--outfile", str(gguf_f32_output)
]
run_command(cmd_convert)
print("Quantizing model to I2_S...")
cmd_quantize = [
str(llama_quantize_binary),
str(gguf_f32_output),
str(gguf_i2s_output),
"I2_S",
"1"
]
run_command(cmd_quantize)
print("Convert successfully.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("Cleaning up intermediate files...")
if preprocessed_output_file.exists() and preprocessed_output_file != input_backup_file:
print(f"Removing preprocessed file: {preprocessed_output_file}")
try:
preprocessed_output_file.unlink()
except OSError as e:
print(f"Warning: Could not remove {preprocessed_output_file}: {e}")
# if gguf_f32_output.exists():
# print(f"Removing f32 GGUF: {gguf_f32_output}")
# try:
# gguf_f32_output.unlink()
# except OSError as e:
# print(f"Warning: Could not remove {gguf_f32_output}: {e}")
if input_backup_file.exists():
if not input_file.exists():
print(f"Restoring original '{input_file}' from '{input_backup_file}'")
try:
shutil.move(input_backup_file, input_file)
except Exception as e:
print(f"Warning: Could not restore {input_file} from backup: {e}")
else:
print(f"Removing backup '{input_backup_file}' as original '{input_file}' should be present.")
try:
input_backup_file.unlink()
except OSError as e:
print(f"Warning: Could not remove backup {input_backup_file}: {e}")
if __name__ == "__main__":
main() | {
"repo_id": "microsoft/BitNet",
"file_path": "utils/convert-helper-bitnet.py",
"license": "MIT License",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/BitNet:utils/preprocess-huggingface-bitnet.py | from safetensors import safe_open
from safetensors.torch import save_file
import torch
def quant_weight_fp16(weight):
weight = weight.to(torch.float)
s = 1.0 / weight.abs().mean().clamp_(min=1e-5)
new_weight = (weight * s).round().clamp(-1, 1) / s
return new_weight
def quant_model(input, output):
tensors = {}
with safe_open(input, framework='pt') as f:
for name in f.keys():
tensors[name] = f.get_tensor(name)
keyword_list = [
'q_proj.weight',
'k_proj.weight',
'v_proj.weight',
'o_proj.weight',
'gate_proj.weight',
'up_proj.weight',
'down_proj.weight'
]
if any(keyword in name for keyword in keyword_list):
print(f'[INFO] Quantizing {name}')
tensors[name] = quant_weight_fp16(tensors[name])
print(f'[INFO] Saving to {output}\nThis may take a while.')
save_file(tensors, output)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Convert Safetensors back to Torch .pth checkpoint")
parser.add_argument(
"--input", type=str, required=True,
)
parser.add_argument(
"--output", type=str, required=True,
)
args = parser.parse_args()
quant_model(
input=args.input,
output=args.output,
) | {
"repo_id": "microsoft/BitNet",
"file_path": "utils/preprocess-huggingface-bitnet.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/BitNet:gpu/convert_checkpoint.py | import json
import os
import re
import sys
from pathlib import Path
from typing import Optional
from dataclasses import dataclass
import torch
from einops import rearrange
from safetensors.torch import save_file
import model
from pack_weight import convert_weight_int8_to_int2
@torch.inference_mode()
def convert_ts_checkpoint(
*,
input_path: str = "",
) -> None:
config = model.ModelArgs()
print(f"Model config {config.__dict__}")
def quant_weight_int8(weight):
s = 1.0 / weight.abs().mean().clamp_(min=1e-5)
new_weight = (weight * s).round().clamp(-1, 1).to(torch.int8)
new_scale = (1.0 / s).to(torch.bfloat16)
return new_weight, new_scale.reshape(1)
def quant_weight_fp16(weight):
s = 1.0 / weight.abs().mean().clamp_(min=1e-5)
new_weight = (weight * s).round().clamp(-1, 1) / s
return new_weight
def convert_int8_to_int2(weight):
return convert_weight_int8_to_int2(weight)
merged_result = torch.load(input_path, map_location="cpu", mmap=True)
int2_result = {}
fp16_result = {}
zero = torch.zeros(1).to(torch.bfloat16)
for key, value in merged_result.items():
if 'wqkv' in key:
wq = value[:config.dim]
wk = value[config.dim:config.dim // config.n_heads * config.n_kv_heads + config.dim]
wv = value[config.dim // config.n_heads * config.n_kv_heads + config.dim:]
wq_weight, wa_scale = quant_weight_int8(wq)
wk_weight, wb_scale = quant_weight_int8(wk)
wv_weight, wc_scale = quant_weight_int8(wv)
wqkv_weight = torch.cat([wq_weight, wk_weight, wv_weight], dim=0)
wqkv_scale = torch.cat([wa_scale, wb_scale, wc_scale, zero], dim=0)
int2_result[key] = convert_int8_to_int2(wqkv_weight)
int2_result[key.replace('weight', 'weight_scale')] = wqkv_scale
wq_weight = quant_weight_fp16(wq)
wk_weight = quant_weight_fp16(wk)
wv_weight = quant_weight_fp16(wv)
wqkv_weight = torch.cat([wq_weight, wk_weight, wv_weight], dim=0)
fp16_result[key] = wqkv_weight
elif 'w13' in key:
w1 = value[:config.ffn_dim]
w3 = value[config.ffn_dim:]
w1_weight, w1_scale = quant_weight_int8(w1)
w3_weight, w3_scale = quant_weight_int8(w3)
w13_weight = torch.cat([w1_weight, w3_weight], dim=0)
w13_scale = torch.cat([w1_scale, w3_scale, zero, zero], dim=0)
int2_result[key] = convert_int8_to_int2(w13_weight)
int2_result[key.replace('weight', 'weight_scale')] = w13_scale
w1_weight = quant_weight_fp16(w1)
w3_weight = quant_weight_fp16(w3)
w13_weight = torch.cat([w1_weight, w3_weight], dim=0)
fp16_result[key] = w13_weight
elif 'w2' in key or 'wo' in key:
weight, scale = quant_weight_int8(value)
scale = torch.cat([scale, zero, zero, zero], dim=0)
int2_result[key] = convert_int8_to_int2(weight)
int2_result[key.replace('weight', 'weight_scale')] = scale
weight = quant_weight_fp16(value)
fp16_result[key] = weight
else:
int2_result[key] = value.clone()
fp16_result[key] = value.clone()
output_dir = os.path.dirname(input_path)
print(f"Saving checkpoint to {output_dir}/model_state_int2.pt")
torch.save(int2_result, f"{output_dir}/model_state_int2.pt")
print(f"Saving checkpoint to {output_dir}/model_state_fp16.pt")
torch.save(fp16_result, f"{output_dir}/model_state_fp16.pt")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Convert TorchScale checkpoint.')
parser.add_argument('--input', type=str)
args = parser.parse_args()
convert_ts_checkpoint(
input_path=args.input,
)
| {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/convert_checkpoint.py",
"license": "MIT License",
"lines": 87,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/BitNet:gpu/convert_safetensors.py | import re
import torch
from pathlib import Path
from safetensors.torch import load_file
from einops import rearrange
from dataclasses import dataclass
from typing import Optional
transformer_configs = {
"2B": dict(n_layer=30, n_head=20, dim=2560, vocab_size=128256, n_local_heads=5, intermediate_size=6912),
}
@dataclass
class ModelArgs:
block_size: int = 4096
vocab_size: int = 32000
n_layer: int = 32
n_head: int = 32
dim: int = 4096
intermediate_size: int = None
n_local_heads: int = -1
head_dim: int = 64
rope_base: float = 10000
norm_eps: float = 1e-5
def __post_init__(self):
if self.n_local_heads == -1:
self.n_local_heads = self.n_head
if self.intermediate_size is None:
hidden_dim = 4 * self.dim
n_hidden = int(2 * hidden_dim / 3)
self.intermediate_size = n_hidden + (256 - n_hidden % 256) if n_hidden % 256 else n_hidden
self.head_dim = self.dim // self.n_head
@classmethod
def from_name(cls, name: str):
if name in transformer_configs:
return cls(**transformer_configs[name])
config = [k for k in transformer_configs if k in name.upper() or k in name]
assert len(config) == 1, f"Unknown model name: {name}"
return cls(**transformer_configs[config[0]])
def invert_convert_q(w: torch.Tensor, config: ModelArgs) -> torch.Tensor:
return rearrange(w, '(h l d) i -> (h d l) i', h=config.n_head, l=2)
def invert_convert_k(w: torch.Tensor, config: ModelArgs) -> torch.Tensor:
return rearrange(w, '(h l d) i -> (h d l) i', h=config.n_local_heads, l=2)
def convert_back(
safetensors_path: str,
output_file: str,
model_name: Optional[str] = None,
):
st_dict = load_file(safetensors_path)
cfg = ModelArgs.from_name(model_name)
print(f"Using model configurations: {cfg}")
recovered: dict = {}
for layer in range(cfg.n_layer):
base = f"model.layers.{layer}."
wq = st_dict[f"{base}self_attn.q_proj.weight"]
wk = st_dict[f"{base}self_attn.k_proj.weight"]
wv = st_dict[f"{base}self_attn.v_proj.weight"]
wq = invert_convert_q(wq, cfg)
wk = invert_convert_k(wk, cfg)
wqkv = torch.cat([wq, wk, wv], dim=0)
recovered[f"layers.{layer}.attention.wqkv.weight"] = wqkv
recovered[f"layers.{layer}.attention.wo.weight"] = st_dict[f"{base}self_attn.o_proj.weight"]
recovered[f"layers.{layer}.attention_norm.weight"] = st_dict[f"{base}input_layernorm.weight"]
recovered[f"layers.{layer}.ffn_norm.weight"] = st_dict[f"{base}post_attention_layernorm.weight"]
recovered[f"layers.{layer}.attention.attn_sub_norm.weight"] = st_dict[f"{base}self_attn.attn_sub_norm.weight"]
recovered[f"layers.{layer}.feed_forward.ffn_sub_norm.weight"] = st_dict[f"{base}mlp.ffn_sub_norm.weight"]
gate = st_dict[f"{base}mlp.gate_proj.weight"]
up = st_dict[f"{base}mlp.up_proj.weight"]
w13 = torch.cat([gate, up], dim=0)
recovered[f"layers.{layer}.feed_forward.w13.weight"] = w13
recovered[f"layers.{layer}.feed_forward.w2.weight"] = st_dict[f"{base}mlp.down_proj.weight"]
recovered["tok_embeddings.weight"] = st_dict["model.embed_tokens.weight"]
recovered["output.weight"] = st_dict["model.embed_tokens.weight"]
recovered["norm.weight"] = st_dict["model.norm.weight"]
print(f"Saving to {output_file}")
torch.save(recovered, output_file)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Convert Safetensors back to Torch .pth checkpoint")
parser.add_argument(
"--safetensors_file", type=str, required=True,
help="Path to input .safetensors file"
)
parser.add_argument(
"--output", type=str, default="./checkpoints/model_state.pt",
help="Path to output .pt file"
)
parser.add_argument(
"--model_name", type=str, default="2B",
help="Model configuration name to use (e.g. 2B)"
)
args = parser.parse_args()
convert_back(
safetensors_path=args.safetensors_file,
output_file=args.output,
model_name=args.model_name,
) | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/convert_safetensors.py",
"license": "MIT License",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/BitNet:gpu/generate.py | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import json
import os
import readline # type: ignore # noqa
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Optional, Tuple, Union
import fire
import model as fast
import torch
from stats import Stats
from tokenizer import Tokenizer, ChatFormat
import sample_utils
from xformers.ops.fmha.attn_bias import (
BlockDiagonalCausalWithOffsetPaddedKeysMask as AttnBias,
)
@dataclass
class GenArgs:
gen_length: int = 32
gen_bsz: int = 1
prompt_length: int = 64
use_sampling: bool = False
temperature: float = 0.8
top_p: float = 0.9
class FastGen:
GRAPH_WARMUPS: int = 1
tokenizer: Tokenizer
@staticmethod
def build(
ckpt_dir: str,
gen_args: GenArgs,
device: Union[torch.device, str],
tokenizer_path: Optional[str] = None,
num_layers: int = 13,
use_full_vocab: bool = False,
) -> "FastGen":
"""
Load a Llama or Code Llama checkpoint and return a new
generator for this model.
"""
start_time = time.time()
model_args_prefill = fast.ModelArgs(use_kernel=False)
model_args_decode = fast.ModelArgs(use_kernel=True)
tokenizer = Tokenizer("./tokenizer.model")
torch.set_default_device(device)
torch.set_default_dtype(torch.bfloat16)
prefill_model = fast.Transformer(model_args_prefill)
decode_model = fast.Transformer(model_args_decode)
fp16_ckpt_path = str(Path(ckpt_dir) / "model_state_fp16.pt")
fp16_checkpoint = torch.load(fp16_ckpt_path, map_location="cpu")
int2_ckpt_path = str(Path(ckpt_dir) / "model_state_int2.pt")
int2_checkpoint = torch.load(int2_ckpt_path, map_location="cpu")
prefill_model.load_state_dict(fp16_checkpoint, strict=True)
decode_model.load_state_dict(int2_checkpoint, strict=True)
torch.cuda.synchronize()
print(f"loaded model in {time.time() - start_time:.2f} seconds")
start_time = time.time()
return FastGen(gen_args, model_args_prefill, prefill_model, decode_model, tokenizer)
def __init__(
self,
args: GenArgs,
model_args: fast.ModelArgs,
prefill_model: fast.Transformer,
decode_model: fast.Transformer,
tokenizer: Tokenizer,
):
self.gen_args = args
self.max_seq_length = args.prompt_length + args.gen_length
self.model_args = model_args
# self.model = model
self.prefill_model = prefill_model
self.decode_model = decode_model
self.tokenizer = tokenizer
self._prefill_cuda_graph, self._prefill_compile_model, self._prefill_inputs, self._prefill_logits = None, None, None, None
self._generate_cuda_graph, self._generate_compile_model, self._generate_inputs, self._generate_logits = None, None, None, None
self._cache = None
start_time = time.time()
self._prefill_compile_model = self.compile_prefill()
self._generate_compile_model = self.compile_generate()
print(f"compiled model in {time.time() - start_time:.2f} seconds")
def compile_prefill(self):
if self._cache is None:
self._cache = fast.make_cache(
args=self.model_args,
length=self.gen_args.gen_bsz * self.max_seq_length,
)
seq_lens = [self.gen_args.prompt_length for _ in range(self.gen_args.gen_bsz)]
bias = AttnBias.from_seqlens(
q_seqlen=seq_lens,
kv_seqlen=seq_lens,
kv_padding=self.max_seq_length,
)
bias.q_seqinfo.to("cuda")
bias.k_seqinfo.to("cuda")
tokens = torch.IntTensor([1] * self.gen_args.gen_bsz * self.gen_args.prompt_length).cuda()
self._prefill_inputs = (tokens, bias)
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
_ = self.prefill_model.forward_with_attn_bias(
token_values=self._prefill_inputs[0],
attn_bias=self._prefill_inputs[1],
cache=self._cache,
)
torch.cuda.current_stream().wait_stream(s)
self._prefill_cuda_graph = torch.cuda.CUDAGraph()
recording_kwargs = {}
if "capture_error_mode" in torch.cuda.graph.__init__.__annotations__:
# In PyTorch 2.1+ and nightlies from late Aug 2023,
# we can do this to maybe avoid watchdog-related crashes
recording_kwargs["capture_error_mode"] = "thread_local"
with torch.cuda.graph(self._prefill_cuda_graph, **recording_kwargs):
self._prefill_logits = self.prefill_model.forward_with_attn_bias(
token_values=self._prefill_inputs[0],
attn_bias=self._prefill_inputs[1],
cache=self._cache,
)
def replay(tokens, seq_lens=None):
self._prefill_inputs[0].copy_(tokens)
if seq_lens is not None:
self._prefill_inputs[1].k_seqinfo.seqlen.copy_(seq_lens)
self._prefill_cuda_graph.replay()
torch.cuda.synchronize()
return self._prefill_logits
return replay
def compile_generate(self):
if self._cache is None:
self._cache = fast.make_cache(
args=self.model_args,
length=self.gen_args.gen_bsz * self.max_seq_length,
)
seq_lens = [1 for _ in range(self.gen_args.gen_bsz)]
kv_seq_lens = [self.gen_args.prompt_length for _ in range(self.gen_args.gen_bsz)]
bias = AttnBias.from_seqlens(
q_seqlen=seq_lens,
kv_seqlen=kv_seq_lens,
kv_padding=self.max_seq_length,
)
bias.q_seqinfo.to("cuda")
bias.k_seqinfo.to("cuda")
tokens = torch.IntTensor([1] * self.gen_args.gen_bsz).cuda()
self._generate_inputs = (tokens, bias)
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
_ = self.decode_model.forward_with_attn_bias(
token_values=self._generate_inputs[0],
attn_bias=self._generate_inputs[1],
cache=self._cache,
)
torch.cuda.current_stream().wait_stream(s)
self._generate_cuda_graph = torch.cuda.CUDAGraph()
recording_kwargs = {}
if "capture_error_mode" in torch.cuda.graph.__init__.__annotations__:
# In PyTorch 2.1+ and nightlies from late Aug 2023,
# we can do this to maybe avoid watchdog-related crashes
recording_kwargs["capture_error_mode"] = "thread_local"
with torch.cuda.graph(self._generate_cuda_graph, **recording_kwargs):
self._generate_logits = self.decode_model.forward_with_attn_bias(
token_values=self._generate_inputs[0],
attn_bias=self._generate_inputs[1],
cache=self._cache,
)
def replay(tokens, seq_lens):
self._generate_inputs[0].copy_(tokens)
self._generate_inputs[1].k_seqinfo.seqlen.copy_(seq_lens)
self._generate_cuda_graph.replay()
return self._generate_logits
return replay
@torch.inference_mode()
def generate_all(
self, prompts: list[list[int]], use_cuda_graphs: bool, use_sampling: bool
) -> Tuple[Stats, list[list[int]]]:
bs = len(prompts)
prompt_lens = [len(p) for p in prompts]
padded_prompt_lens = [self.gen_args.prompt_length] * bs
max_prompt_length = max(prompt_lens)
gen_length = self.gen_args.gen_length
max_seq_length = max_prompt_length + gen_length
print(max_prompt_length, gen_length)
bias = AttnBias.from_seqlens(
q_seqlen=padded_prompt_lens,
kv_seqlen=prompt_lens,
kv_padding=max_seq_length,
)
bias.q_seqinfo.to("cuda")
bias.k_seqinfo.to("cuda")
# Input tensors to the cuda graph
kv_seqlen = bias.k_seqinfo.seqlen
prompts = [prompt + [1] * (self.gen_args.prompt_length - len(prompt)) for prompt in prompts]
tokens = torch.IntTensor(sum(prompts, [])).cuda()
out_tokens = torch.zeros((max_seq_length, bs), dtype=torch.int)
stats = Stats()
torch.cuda.synchronize()
stats.phase("prefill" if use_cuda_graphs else "total")
# stats.phase("total")
output = self._prefill_compile_model(tokens, None)
logits = output[kv_seqlen - 1, :]
logits = logits.view(bs, self.model_args.vocab_size)
if use_sampling:
temp = 0.7
top_p = 0.95
probs = torch.softmax(logits / temp, dim=-1)
next_token = sample_utils.top_p(probs, top_p)
else:
next_token = torch.argmax(logits, dim=-1)
next_token = next_token.reshape(bs)
out_tokens[0, :] = next_token
torch.cuda.synchronize()
stats.phase("decode" if use_cuda_graphs else "total")
eos_id = self.tokenizer.eot_id
for niter in range(1, gen_length):
kv_seqlen.add_(kv_seqlen < max_seq_length)
output = self._generate_compile_model(next_token, kv_seqlen)
logits = output.view(bs, self.model_args.vocab_size)
if use_sampling:
temp = 0.7
top_p = 0.95
probs = torch.softmax(logits / temp, dim=-1)
next_token = sample_utils.top_p(probs, top_p)
else:
next_token = torch.argmax(logits, dim=-1)
next_token = next_token.reshape(bs)
out_tokens[niter, :] = next_token
if next_token.eq(eos_id).any():
break
torch.cuda.synchronize()
stats.end_phase(tokens=niter * bs)
def trim_answer(prompt_len, tokens):
# print(prompt, tokens)
"""Trim the answer to end it on an eos token."""
tokens = tokens[: max_seq_length - prompt_len]
eos_id = self.tokenizer.eot_id
if eos_id in tokens:
return tokens[: tokens.index(eos_id) + 1]
else:
return tokens
answers = [
trim_answer(prompt_len, answer)
for prompt_len, answer in zip(prompt_lens, out_tokens.t().tolist())
]
return stats, answers
def get_prompts(interactive: bool) -> Iterable[list[str]]:
if interactive:
while True:
try:
prompts = input("enter prompt: ").split("\n")
except EOFError:
print("exiting")
sys.exit(0)
yield prompts
else:
yield [
"Hello, my name is",
]
def main(ckpt_dir: str, interactive: bool = False, chat_format: bool = False, sampling: bool = False):
local_rank = 0
device = f"cuda:{local_rank}"
torch.cuda.set_device(local_rank)
g = FastGen.build(ckpt_dir, GenArgs(), device)
if chat_format:
g.tokenizer = ChatFormat(g.tokenizer)
for prompts in get_prompts(interactive):
# prompts = [f"{prompt}\n" for prompt in prompts]
if chat_format:
# prompts = [f'<|begin_of_text|>User: {prompt}<|eot_id|>Assistant: ' for prompt in prompts]
tokens = [g.tokenizer.encode_dialog_prompt(dialog=[{"role": "user", "content": prompt}], completion=True) for prompt in prompts]
else:
tokens = [g.tokenizer.encode(x, bos=False, eos=False) for x in prompts]
print(tokens)
stats, out_tokens = g.generate_all(
tokens, use_cuda_graphs="NO_CUDA_GRAPHS" not in os.environ, use_sampling=sampling,
)
for i, prompt in enumerate(prompts):
print(f"> {prompt}")
answer = g.tokenizer.decode(out_tokens[i])
print(answer)
print("---------------")
for phase_stats in stats.phases:
print(phase_stats.show())
print(f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB")
if __name__ == "__main__":
fire.Fire(main) | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/generate.py",
"license": "MIT License",
"lines": 288,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/BitNet:gpu/model.py | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import functional as F
from xformers.ops import RMSNorm, fmha, rope_padded
from xformers.ops.fmha.attn_bias import (
BlockDiagonalCausalWithOffsetPaddedKeysMask as AttnBias,
)
import ctypes
bitnet_lib = ctypes.CDLL('bitnet_kernels/libbitnet.so')
def bitnet_int8xint2_linear(input0, input1, s, ws):
out_shape = list(input0.shape)
out_shape[-1] = input1.shape[0]
stream = torch.cuda.current_stream()
M = input0.shape[0]
if len(out_shape) == 3:
M *= input0.shape[1]
N = input1.shape[0]
K = input1.shape[1] * 4
ret = torch.zeros(*out_shape, dtype=torch.bfloat16, device=input0.device)
bitnet_lib.bitlinear_int8xint2(*[ctypes.c_void_p(input0.data_ptr()), ctypes.c_void_p(input1.data_ptr()), ctypes.c_void_p(ret.data_ptr()), ctypes.c_void_p(s.data_ptr()), ctypes.c_void_p(ws.data_ptr()), ctypes.c_int(M), ctypes.c_int(N), ctypes.c_int(K), ctypes.c_void_p(stream.cuda_stream)])
return ret
@dataclass
class ModelArgs:
dim: int = 2560
n_layers: int = 30
n_heads: int = 20
n_kv_heads: int = 5
vocab_size: int = 128256
ffn_dim: int = 6912
norm_eps: float = 1e-5
rope_theta: float = 500000.0
use_kernel: bool = False
LayerCache = Tuple[torch.Tensor, torch.Tensor]
class BitLinearKernel(nn.Module):
in_features: int
out_features: int
weight: torch.Tensor
weight_scale: torch.Tensor
def __init__(self, in_features: int, out_features: int, bias: bool = False):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = torch.nn.Parameter(torch.zeros(out_features, in_features//4, dtype=torch.int8), requires_grad=False)
self.weight_scale = torch.nn.Parameter(torch.zeros(4, dtype=torch.bfloat16), requires_grad=False)
@torch.compile
def quant_input(self, input):
s = 127 / input.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
return (input * s).round().clamp(-128, 127).to(torch.int8), s
def forward(self, input):
input, s = self.quant_input(input)
return bitnet_int8xint2_linear(input, self.weight, s, self.weight_scale)
class BitLinear(nn.Linear):
@torch.compile
def quant_input(self, input):
s = 127 / input.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
return (input * s).round().clamp(-128, 127) / s
def forward(self, input):
input = self.quant_input(input)
return F.linear(input, self.weight)
class Attention(nn.Module):
def __init__(
self,
dim: int,
head_dim: int,
n_heads: int,
n_kv_heads: int,
rope_theta: float,
norm_eps: float,
use_kernel: bool,
):
super().__init__()
self.head_dim = head_dim
self.rope_theta = rope_theta
self.n_local_heads = n_heads
self.n_local_kv_heads = n_kv_heads
Linear = BitLinearKernel if use_kernel else BitLinear
self.wqkv = Linear(
dim,
(self.n_local_heads + 2 * self.n_local_kv_heads) * head_dim,
bias=False,
)
self.wo = Linear(
self.n_local_heads * head_dim,
dim,
bias=False,
)
self.attn_sub_norm = RMSNorm(dim, norm_eps)
def forward(
self,
x: torch.Tensor,
cache: LayerCache,
attn_bias: AttnBias,
) -> torch.Tensor:
xqkv = self.wqkv(x)
xq = xqkv[:, : (self.n_local_heads * self.head_dim)]
xkv = xqkv[:, (self.n_local_heads * self.head_dim) :]
xk, xv = xkv.chunk(2, 1)
output_shape = xq.shape
heads_per_group = self.n_local_heads // self.n_local_kv_heads
xq = xq.view(
1, xq.shape[0], self.n_local_kv_heads, heads_per_group, self.head_dim
)
xk = xk.view(1, xk.shape[0], self.n_local_kv_heads, 1, self.head_dim)
# xq = rearrange(xq, 'b (g h l d) -> 1 b h g (d l)', g=heads_per_group, h=self.n_local_kv_heads, d=self.head_dim // 2, l=2)
# xk = rearrange(xk, 'b (g l d) -> 1 b g 1 (d l)', g=self.n_local_kv_heads, d=self.head_dim // 2)
xv = xv.view(1, xv.shape[0], self.n_local_kv_heads, 1, self.head_dim)
cache_k, cache_v = cache
xq = rope_padded(
xq=xq,
xk=xk,
xv=xv,
cache_k=cache_k,
cache_v=cache_v,
attn_bias=attn_bias,
theta=self.rope_theta,
)
output = fmha.memory_efficient_attention_forward(
xq, cache_k, cache_v, attn_bias, op = fmha.flash.FwOp
)
output = output.reshape(output_shape)
output = self.attn_sub_norm(output)
output = self.wo(output)
return output
@torch.compile
def squared_relu(x: torch.Tensor) -> torch.Tensor:
return F.relu(x) ** 2
class FeedForward(nn.Module):
def __init__(
self,
dim: int,
hidden_dim: int,
norm_eps: float,
use_kernel: bool,
):
super().__init__()
Linear = BitLinearKernel if use_kernel else BitLinear
self.w13 = Linear(
dim,
2 * hidden_dim,
bias=False,
)
self.w2 = Linear(
hidden_dim,
dim,
bias=False,
)
self.ffn_sub_norm = RMSNorm(hidden_dim, norm_eps)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x13 = self.w13(x)
x1, x3 = x13.chunk(2, -1)
inner = self.ffn_sub_norm(squared_relu(x1) * x3)
output = self.w2(inner)
return output
class TransformerBlock(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
assert args.dim % args.n_heads == 0
head_dim = args.dim // args.n_heads
if args.n_kv_heads is not None:
n_kv_heads = args.n_kv_heads
else:
n_kv_heads = args.n_heads
assert args.n_heads % n_kv_heads == 0
self.attention = Attention(
dim=args.dim,
head_dim=head_dim,
n_heads=args.n_heads,
n_kv_heads=n_kv_heads,
rope_theta=args.rope_theta,
norm_eps=args.norm_eps,
use_kernel=args.use_kernel,
)
self.feed_forward = FeedForward(
dim=args.dim,
hidden_dim=args.ffn_dim,
norm_eps=args.norm_eps,
use_kernel=args.use_kernel,
)
self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
def forward(
self,
x: torch.Tensor,
cache: LayerCache,
attn_bias: AttnBias,
) -> torch.Tensor:
h = x + self.attention.forward(
self.attention_norm(x),
cache,
attn_bias,
)
out = h + self.feed_forward(self.ffn_norm(h))
return out
class Transformer(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
assert args.vocab_size > 0
self.tok_embeddings = nn.Embedding(
num_embeddings=args.vocab_size,
embedding_dim=args.dim,
)
self.layers = nn.ModuleList()
for _ in range(args.n_layers):
self.layers.append(TransformerBlock(args))
self.norm = RMSNorm(args.dim, eps=args.norm_eps)
self.output = nn.Linear(
args.dim,
args.vocab_size,
bias=False,
)
@torch.no_grad()
def forward_with_attn_bias(
self,
token_values: torch.Tensor,
attn_bias: AttnBias,
cache: list[LayerCache],
) -> torch.Tensor:
h = self.tok_embeddings(token_values)
for i, layer in enumerate(self.layers):
h = layer(h, cache[i], attn_bias)
logits = self.output(self.norm(h))
return logits.float()
def forward(
self,
token_values: torch.Tensor,
token_lengths: torch.Tensor,
start_pos: torch.Tensor,
cache: list[LayerCache],
kv_padding: int,
) -> torch.Tensor:
attn_bias = AttnBias.from_seqlens(
q_seqlen=token_lengths.tolist(),
kv_seqlen=(start_pos + token_lengths).tolist(),
kv_padding=kv_padding,
)
return self.forward_with_attn_bias(token_values, attn_bias, cache)
def make_cache(
args: ModelArgs,
length: int,
device: Optional[Union[str, torch.device]] = None,
n_layers: Optional[int] = None,
dtype: Optional[torch.dtype] = None,
) -> list[LayerCache]:
"""
Allocate a cache to be used with the Transformer module.
Args:
args (ModelArgs): the model configuration.
length (int): per layer cache size.
It is usually budgeted as ``max_batch * max_seq``
device (torch.device, optional): the device on which
the cache should be allocated.
n_layers (int, optional): the number of layers to
allocate a cache for (defaults to the model
settings).
dtype (torch.dtype, optional): the dtype to use for
cache entries (defaults to the default dtype).
Returns:
The cache object to pass to ``Tranformer.forward``.
"""
head_dim = args.dim // args.n_heads
n_kv_heads = args.n_kv_heads
if n_kv_heads is None:
n_kv_heads = args.n_heads
n_local_kv_heads = n_kv_heads
if n_layers is None:
n_layers = args.n_layers
shape = (1, length, n_local_kv_heads, 1, head_dim)
heads_per_group = args.n_heads // n_kv_heads
expansion = (-1, -1, -1, heads_per_group, -1)
return [
(
torch.zeros(shape, device=device, dtype=dtype).expand(expansion),
torch.zeros(shape, device=device, dtype=dtype).expand(expansion),
)
for _ in range(n_layers)
]
def cache_prefix(cache: list[LayerCache], length: int) -> list[LayerCache]:
"""
Take a prefix view of a larger cache.
The original cache object remains of identical size and valid
after the shrinked alias has been used. This function is useful
when a cache was allocated for a larger batch size than what is
necessary.
Args:
cache: the cache to take a view in.
length (int): the desired length
Returns:
A view in the input cache object.
"""
if len(cache) > 0:
assert cache[0][0].shape[1] >= length
return [(ck[:, :length], cv[:, :length]) for ck, cv in cache] | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/model.py",
"license": "MIT License",
"lines": 298,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/BitNet:gpu/pack_weight.py | import torch
import numpy as np
def B_global_16x32_to_shared_load_16x32_layout(i, j):
"""
stride * 8 * (tx // HALF_WARP_expr)
+ (tx % 8) * stride
+ 16 * ((tx % HALF_WARP_expr) // 8)
"""
thread_id = i * 2 + j // 16
row = (thread_id // 16) * 8 + (thread_id % 8)
col = (j % 16) + 16 * ((thread_id % 16) // 8)
return row, col
def permutate_weight_fastest(weight):
wmma_n = 16
wmma_k = 32
N = weight.shape[0]
K = weight.shape[1]
# Create a lookup table for the permutation
mapping = np.zeros((wmma_n, wmma_k, 2), dtype=int)
for ii in range(wmma_n):
for jj in range(wmma_k):
mapping[ii, jj] = B_global_16x32_to_shared_load_16x32_layout(ii, jj)
# Reshape weight for the final format
permutated_weight = np.zeros((N // wmma_n, K // wmma_k, wmma_n, wmma_k), dtype="int8")
# Use advanced indexing for the entire operation
i_indices = np.arange(N // wmma_n)[:, np.newaxis, np.newaxis, np.newaxis]
j_indices = np.arange(K // wmma_k)[np.newaxis, :, np.newaxis, np.newaxis]
# Create the source indices
src_i = i_indices * wmma_n + mapping[:, :, 0]
src_j = j_indices * wmma_k + mapping[:, :, 1]
# Extract and reshape in one go
permutated_weight = weight[src_i, src_j]
return permutated_weight
def compress_int2_to_int8(int2_weight):
int8_weight = np.zeros(
(*int2_weight.shape[:-1], int2_weight.shape[-1] // 4), dtype=np.int8
)
for j in range(int2_weight.shape[-1] // 4):
for k in range(4):
int8_weight[:, :, :, j] |= int2_weight[:, :, :, j * 4 + k] << (k * 2)
return int8_weight
def interleave_weight_int8(qweight, nbits=2):\
# reinterpret the data type of qweight to int32
# shift = [ 0, 8, 16, 24, 2, 10, 18, 26, 4, 12, 20, 28, 6, 14, 22, 30]
# index: [ 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]
qweight = qweight.view(np.int32)
new_qweight = np.zeros_like(qweight)
bits_stride = 8
mask = (1 << nbits) - 1 # for 4bit the val is 0x0000000f
num_groups = 32 // bits_stride # 4
elems_per_group = bits_stride // nbits # 4
for i in range(num_groups):
for j in range(elems_per_group):
offset = i * elems_per_group + j
shift = (offset % num_groups) * bits_stride + (offset // num_groups) * nbits
new_qweight |= ((qweight >> (nbits * offset)) & mask) << shift
return new_qweight.view(np.int8)
def convert_weight_int8_to_int2(weight):
N = weight.shape[0]
K = weight.shape[1]
weight = weight+2
weight = weight.cpu().numpy()
# print(weight)
# print(torch.max(weight), torch.min(weight))
# permutated_weight_slow = permutate_weight(weight)
permutated_weight = permutate_weight_fastest(weight)
# assert np.all(permutated_weight_slow == permutated_weight)
# print("Permutation is correct")
compressed_weight = compress_int2_to_int8(permutated_weight)
interleaved_weight = interleave_weight_int8(compressed_weight, 2)
ret = torch.from_numpy(interleaved_weight)
ret = torch.reshape(ret, (N, K // 4))
return ret
| {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/pack_weight.py",
"license": "MIT License",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/BitNet:gpu/sample_utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import torch
@torch.compile
def top_p(probs: torch.Tensor, p: float) -> torch.Tensor:
"""
Perform top-p (nucleus) sampling on a probability distribution.
Args:
probs (torch.Tensor): probability distribution tensor.
p (float): probability threshold for top-p sampling.
Returns:
torch.Tensor: sampled token indices.
Note:
Top-p sampling selects the smallest set of tokens whose cumulative
probability mass exceeds the threshold p. The distribution is
renormalized based on the selected tokens.
"""
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_sort > p
probs_sort[mask] = 0.0
next_token = torch.multinomial(probs_sort, num_samples=1)
next_token = torch.gather(probs_idx, -1, next_token)
return next_token | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/sample_utils.py",
"license": "MIT License",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/BitNet:gpu/stats.py | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import time
from dataclasses import dataclass
from typing import Optional
@dataclass
class PhaseStats:
name: str
tokens: int
time: float
def show(self) -> str:
tps = self.tokens / self.time
return (
f"[{self.name}] "
f"generated tokens: {self.tokens}"
f" - total time: {self.time:.3f}s"
f" - {tps:.1f} tokens per second"
)
class Stats:
"""
Generation stats, split by phases.
"""
def __init__(self):
self.phases = []
self.current = None
def end_phase(self, tokens: int, now: Optional[float] = None):
"""Terminate the current phase."""
if self.current is None:
return
if now is None:
now = time.time()
cname, ctokens, ctime = self.current
stats = PhaseStats(
name=cname,
tokens=tokens - ctokens,
time=now - ctime,
)
self.phases.append(stats)
def phase(self, name: str, tokens: int = 0):
"""
Start a new phase, and terminate the current one,
if one is ongoing.
"""
now = time.time()
self.end_phase(tokens, now)
self.current = (name, tokens, now) | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/stats.py",
"license": "MIT License",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/BitNet:gpu/test.py | import torch
from torch.utils import benchmark
from torch import nn
from pack_weight import convert_weight_int8_to_int2
from torch.profiler import profile, record_function, ProfilerActivity
import ctypes
import numpy as np
# set all seed
torch.manual_seed(42)
np.random.seed(42)
bitnet_lib = ctypes.CDLL('bitnet_kernels/libbitnet.so')
def bitnet_int8xint2_linear(input0, input1, s, ws, ret):
out_shape = list(input0.shape)
out_shape[-1] = input1.shape[0]
stream = torch.cuda.current_stream()
M = input0.shape[0]
if len(out_shape) == 3:
M *= input0.shape[1]
N = input1.shape[0]
K = input1.shape[1] * 4
bitnet_lib.bitlinear_int8xint2(*[ctypes.c_void_p(input0.data_ptr()), ctypes.c_void_p(input1.data_ptr()), ctypes.c_void_p(ret.data_ptr()), ctypes.c_void_p(s.data_ptr()), ctypes.c_void_p(ws.data_ptr()), ctypes.c_int(M), ctypes.c_int(N), ctypes.c_int(K), ctypes.c_void_p(stream.cuda_stream)])
return ret
if __name__ == '__main__':
test_list = [
(2560, 2560),
(3840, 2560),
(13824, 2560),
(2560, 6912) ,
(3200, 3200),
(4800, 3200),
(3200, 10240),
(20480, 3200),
]
for N,K in test_list:
weight = torch.randint(-1, 2, (N, K), dtype=torch.int8, device='cuda')
weight_scale = torch.ones(1, dtype=torch.bfloat16, device='cuda')
weight_compressed = convert_weight_int8_to_int2(weight).to('cuda')
for i in range(1):
input0 = torch.randint(-128,127,(1, K),dtype=torch.int8, device='cuda')
input0_bf16 = input0.to(torch.bfloat16)
input_np = input0.cpu().to(torch.int32).numpy()
weight_np = weight.cpu().to(torch.int32).T.numpy()
out_np = np.matmul(input_np,weight_np)
out_np = torch.tensor(out_np).cuda().to(torch.bfloat16)
s = torch.ones(1, dtype=torch.bfloat16, device='cuda')
ws = torch.ones(6, dtype=torch.bfloat16, device='cuda')
ret = torch.empty((1,N), dtype=torch.bfloat16, device=input0.device)
out = bitnet_int8xint2_linear(input0, weight_compressed, s, ws, ret)
print(f'custom == np {torch.all(out==out_np)}')
input0 = torch.randint(-128,127,(1, K),dtype=torch.int8, device='cuda')
input0_fp16 = input0.to(torch.float16)
input0_bf16 = input0.to(torch.bfloat16)
weight_fp16 = weight.to(torch.float16).T
weight_bf16 = weight.to(torch.bfloat16).T
ret = torch.empty((1,N), dtype=torch.bfloat16, device=input0.device)
s = torch.ones(1, dtype=torch.bfloat16, device='cuda')
ws = torch.ones(6, dtype=torch.bfloat16, device='cuda')
t0 = benchmark.Timer(
stmt="bitnet_int8xint2_linear(input0, weight_compressed, s, ws, ret)",
setup="from __main__ import input0, weight_compressed, s, ws, ret, bitnet_int8xint2_linear",
num_threads=1,
)
t1 = benchmark.Timer(
stmt="torch.matmul(input0_bf16,weight_bf16)",
setup="from __main__ import input0_bf16, weight_bf16",
num_threads=1,
)
time0 = t0.timeit(50)
time1 = t1.timeit(50)
print(f'Shape{N,K}, W2A8: {time0.mean * 1e6:.2f}us, torch BF16: {time1.mean * 1e6:.2f}us')
# activities = [ ProfilerActivity.CUDA,
# # ProfilerActivity.CPU
# ]
# sort_by_keyword = 'cuda' + "_time_total"
# with profile(activities=activities, record_shapes=True) as prof:
# with record_function("model_inference1"):
# for _ in range(10):
# bitnet_int8xint2_linear(input0, weight_compressed, s, ws, ret)
# torch.matmul(input0_fp16,weight_fp16)
# torch.matmul(input0_bf16,weight_bf16)
# print(prof.key_averages().table(sort_by=sort_by_keyword, row_limit=15))
| {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/test.py",
"license": "MIT License",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/BitNet:gpu/tokenizer.py | import os
from logging import getLogger
from pathlib import Path
from typing import (
AbstractSet,
cast,
Collection,
Dict,
Iterator,
List,
Literal,
Sequence,
TypedDict,
Union,
)
import tiktoken
from tiktoken.load import load_tiktoken_bpe
logger = getLogger(__name__)
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
Dialog = Sequence[Message]
class Tokenizer:
"""
Tokenizing and encoding/decoding text using the Tiktoken tokenizer.
"""
special_tokens: Dict[str, int]
num_reserved_special_tokens = 256
pat_str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" # noqa: E501
def __init__(self, model_path: str):
"""
Initializes the Tokenizer with a Tiktoken model.
Args:
model_path (str): The path to the Tiktoken model file.
"""
assert os.path.isfile(model_path), model_path
mergeable_ranks = load_tiktoken_bpe(model_path)
num_base_tokens = len(mergeable_ranks)
special_tokens = [
"<|begin_of_text|>",
"<|end_of_text|>",
"<|reserved_special_token_0|>",
"<|reserved_special_token_1|>",
"<|reserved_special_token_2|>",
"<|reserved_special_token_3|>",
"<|start_header_id|>",
"<|end_header_id|>",
"<|reserved_special_token_4|>",
"<|eot_id|>", # end of turn
] + [
f"<|reserved_special_token_{i}|>"
for i in range(5, self.num_reserved_special_tokens - 5)
]
self.special_tokens = {
token: num_base_tokens + i for i, token in enumerate(special_tokens)
}
self.model = tiktoken.Encoding(
name=Path(model_path).name,
pat_str=self.pat_str,
mergeable_ranks=mergeable_ranks,
special_tokens=self.special_tokens,
)
logger.info(f"Reloaded tiktoken model from {model_path}")
self.n_words: int = self.model.n_vocab
# BOS / EOS token IDs
self.bos_id: int = self.special_tokens["<|begin_of_text|>"]
self.eos_id: int = self.special_tokens["<|end_of_text|>"]
self.pad_id: int = self.n_words - 1
self.stop_tokens = {
self.special_tokens["<|end_of_text|>"],
self.special_tokens["<|eot_id|>"],
}
logger.info(
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
)
def encode(
self,
s: str,
*,
bos: bool,
eos: bool,
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = (),
) -> List[int]:
"""
Encodes a string into a list of token IDs.
Args:
s (str): The input string to be encoded.
bos (bool): Whether to prepend the beginning-of-sequence token.
eos (bool): Whether to append the end-of-sequence token.
allowed_tokens ("all"|set[str]): allowed special tokens in string
disallowed_tokens ("all"|set[str]): special tokens that raise an error when in string
Returns:
list[int]: A list of token IDs.
By default, setting disallowed_special=() encodes a string by ignoring
special tokens. Specifically:
- Setting `disallowed_special` to () will cause all text corresponding
to special tokens to be encoded as natural text (insteading of raising
an error).
- Setting `allowed_special` to "all" will treat all text corresponding
to special tokens to be encoded as special tokens.
"""
assert type(s) is str
# The tiktoken tokenizer can handle <=400k chars without
# pyo3_runtime.PanicException.
TIKTOKEN_MAX_ENCODE_CHARS = 400_000
# https://github.com/openai/tiktoken/issues/195
# Here we iterate over subsequences and split if we exceed the limit
# of max consecutive non-whitespace or whitespace characters.
MAX_NO_WHITESPACES_CHARS = 25_000
substrs = (
substr
for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS)
for substr in self._split_whitespaces_or_nonwhitespaces(
s[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
)
)
t: List[int] = []
for substr in substrs:
t.extend(
self.model.encode(
substr,
allowed_special=allowed_special,
disallowed_special=disallowed_special,
)
)
if bos:
t.insert(0, self.bos_id)
if eos:
t.append(self.eos_id)
return t
def decode(self, t: Sequence[int]) -> str:
"""
Decodes a list of token IDs into a string.
Args:
t (List[int]): The list of token IDs to be decoded.
Returns:
str: The decoded string.
"""
# Typecast is safe here. Tiktoken doesn't do anything list-related with the sequence.
return self.model.decode(cast(List[int], t))
@staticmethod
def _split_whitespaces_or_nonwhitespaces(
s: str, max_consecutive_slice_len: int
) -> Iterator[str]:
"""
Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len`
consecutive whitespaces or consecutive non-whitespaces.
"""
current_slice_len = 0
current_slice_is_space = s[0].isspace() if len(s) > 0 else False
slice_start = 0
for i in range(len(s)):
is_now_space = s[i].isspace()
if current_slice_is_space ^ is_now_space:
current_slice_len = 1
current_slice_is_space = is_now_space
else:
current_slice_len += 1
if current_slice_len > max_consecutive_slice_len:
yield s[slice_start:i]
slice_start = i
current_slice_len = 1
yield s[slice_start:]
class ChatFormat:
def __init__(self, tokenizer: Tokenizer):
self.tokenizer = tokenizer
self.eot_id = tokenizer.special_tokens["<|eot_id|>"]
def decode(self, tokens: List[int]) -> str:
# Decode the tokens to a string.
decoded_str = self.tokenizer.decode(tokens)
# Remove the special tokens from the decoded string.
decoded_str = decoded_str.replace("<|eot_id|>", "")
return decoded_str
def encode_header(self, message: Message) -> List[int]:
tokens = []
if message["role"] == "system":
tokens.extend(self.tokenizer.encode("System: ", bos=False, eos=False))
elif message["role"] == "user":
tokens.extend(self.tokenizer.encode("User: ", bos=False, eos=False))
elif message["role"] == "assistant":
tokens.extend(self.tokenizer.encode("Assistant: ", bos=False, eos=False))
else:
raise NotImplementedError(f"Role {message['role']} not implemented.")
# tokens.append(self.tokenizer.special_tokens["<|start_header_id|>"])
# tokens.extend(self.tokenizer.encode(message["role"], bos=False, eos=False))
# tokens.append(self.tokenizer.special_tokens["<|end_header_id|>"])
# tokens.extend(self.tokenizer.encode("\n\n", bos=False, eos=False))
return tokens
def encode_message(self, message: Message, return_target=False) -> List[int]:
tokens, targets = [], []
headers = self.encode_header(message)
contents = self.tokenizer.encode(message["content"].strip(), bos=False, eos=False)
contents.append(self.tokenizer.special_tokens["<|eot_id|>"])
tokens = headers + contents
if message["role"] == "assistant":
targets = [-1] * len(headers) + contents
else:
targets = [-1] * len(tokens)
if return_target:
return tokens, targets
return tokens, None
def encode_dialog_prompt(self, dialog: Dialog, completion=False, return_target=False) -> List[int]:
tokens = [self.tokenizer.special_tokens["<|begin_of_text|>"]]
targets = [-1]
for message in dialog:
_tokens, _targets = self.encode_message(message, return_target=return_target)
tokens.extend(_tokens)
if _targets is not None:
targets.extend(_targets)
# Add the start of an assistant message for the model to complete.
if completion:
tokens.extend(self.encode_header({"role": "assistant", "content": ""}))
if return_target:
return tokens, targets
return tokens | {
"repo_id": "microsoft/BitNet",
"file_path": "gpu/tokenizer.py",
"license": "MIT License",
"lines": 217,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/BitNet:run_inference_server.py | import os
import sys
import signal
import platform
import argparse
import subprocess
def run_command(command, shell=False):
"""Run a system command and ensure it succeeds."""
try:
subprocess.run(command, shell=shell, check=True)
except subprocess.CalledProcessError as e:
print(f"Error occurred while running command: {e}")
sys.exit(1)
def run_server():
build_dir = "build"
if platform.system() == "Windows":
server_path = os.path.join(build_dir, "bin", "Release", "llama-server.exe")
if not os.path.exists(server_path):
server_path = os.path.join(build_dir, "bin", "llama-server")
else:
server_path = os.path.join(build_dir, "bin", "llama-server")
command = [
f'{server_path}',
'-m', args.model,
'-c', str(args.ctx_size),
'-t', str(args.threads),
'-n', str(args.n_predict),
'-ngl', '0',
'--temp', str(args.temperature),
'--host', args.host,
'--port', str(args.port),
'-cb' # Enable continuous batching
]
if args.prompt:
command.extend(['-p', args.prompt])
# Note: -cnv flag is removed as it's not supported by the server
print(f"Starting server on {args.host}:{args.port}")
run_command(command)
def signal_handler(sig, frame):
print("Ctrl+C pressed, shutting down server...")
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
parser = argparse.ArgumentParser(description='Run llama.cpp server')
parser.add_argument("-m", "--model", type=str, help="Path to model file", required=False, default="models/bitnet_b1_58-3B/ggml-model-i2_s.gguf")
parser.add_argument("-p", "--prompt", type=str, help="System prompt for the model", required=False)
parser.add_argument("-n", "--n-predict", type=int, help="Number of tokens to predict", required=False, default=4096)
parser.add_argument("-t", "--threads", type=int, help="Number of threads to use", required=False, default=2)
parser.add_argument("-c", "--ctx-size", type=int, help="Size of the context window", required=False, default=2048)
parser.add_argument("--temperature", type=float, help="Temperature for sampling", required=False, default=0.8)
parser.add_argument("--host", type=str, help="IP address to listen on", required=False, default="127.0.0.1")
parser.add_argument("--port", type=int, help="Port to listen on", required=False, default=8080)
args = parser.parse_args()
run_server()
| {
"repo_id": "microsoft/BitNet",
"file_path": "run_inference_server.py",
"license": "MIT License",
"lines": 54,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/VibeVoice:vllm_plugin/tests/test_api_auto_recover.py | #!/usr/bin/env python3
"""
Test VibeVoice vLLM API with Streaming, Hotwords, and Auto-Recovery.
This script tests ASR transcription with automatic recovery from repetition loops.
Supports optional hotwords to improve recognition of domain-specific terms.
Features:
- Streaming output with real-time repetition detection
- Auto-recovery when model enters repetition loops
- Optional hotwords support (embedded in prompt as "with extra info: {hotwords}")
- Video file support (auto-extracts audio)
Recovery Strategy:
1. First attempt: greedy decoding (temperature=0, top_p=1.0)
2. If loop detected: retry with temperature=0.2/0.3/0.4, top_p=0.95
3. Max 3 retries, truncate to last complete segment boundary
Usage:
python test_api_auto_recover.py <audio_path> [output_path] [--url URL] [--hotwords "word1,word2"] [--debug]
Examples:
# Basic usage
python3 test_api_auto_recover.py audio.wav
# With hotwords
python3 test_api_auto_recover.py audio.wav --hotwords "Microsoft,VibeVoice"
# Save result to file
python3 test_api_auto_recover.py audio.wav result.txt
# Debug mode (show recovery info)
python3 test_api_auto_recover.py audio.wav --debug
"""
import requests
import json
import base64
import time
import sys
import os
import subprocess
import re
import argparse
from collections import Counter
def _guess_mime_type(path: str) -> str:
ext = os.path.splitext(path)[1].lower()
if ext == ".wav":
return "audio/wav"
if ext in (".mp3",):
return "audio/mpeg"
if ext in (".m4a",):
return "audio/mp4"
if ext in (".mp4", ".m4v", ".mov", ".webm"):
return "video/mp4"
if ext in (".flac",):
return "audio/flac"
if ext in (".ogg", ".opus"):
return "audio/ogg"
return "application/octet-stream"
def _get_duration_seconds_ffprobe(path: str) -> float:
cmd = [
"ffprobe", "-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
path,
]
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8").strip()
return float(out)
def _extract_audio_from_video(video_path: str) -> str:
"""
Extract audio from video file (mp4/mov/webm) to a temporary mp3 file.
Returns the path to the extracted audio file.
"""
import tempfile
# Create temp file with .mp3 extension
fd, audio_path = tempfile.mkstemp(suffix=".mp3")
os.close(fd)
cmd = [
"ffmpeg", "-y", "-i", video_path,
"-vn", # No video
"-acodec", "libmp3lame",
"-q:a", "2", # High quality
audio_path
]
subprocess.run(cmd, check=True, capture_output=True)
return audio_path
def _is_video_file(path: str) -> bool:
"""Check if the file is a video file that needs audio extraction."""
ext = os.path.splitext(path)[1].lower()
return ext in (".mp4", ".m4v", ".mov", ".webm", ".avi", ".mkv")
def _find_last_segment_boundary(text: str) -> int:
"""
Find the position after the last complete segment boundary (},).
Returns -1 if no complete segment found.
"""
# Find last "}, " or "}," pattern (segment separator)
pos = text.rfind("},")
if pos != -1:
return pos + 2 # Include the },
return -1
def _find_safe_print_boundary(text: str, max_pos: int) -> int:
"""
Find the last complete segment boundary before max_pos.
Returns 0 if no complete segment found before max_pos.
"""
search_text = text[:max_pos]
pos = search_text.rfind("},")
if pos != -1:
return pos + 2 # Include the },
return 0
class RepetitionDetector:
"""Detect repetition patterns in streaming text."""
def __init__(self,
min_pattern_len: int = 10, # Minimum chars for a pattern
min_repeats: int = 3, # Minimum repetitions to trigger
window_size: int = 500): # Window to check for patterns
self.min_pattern_len = min_pattern_len
self.min_repeats = min_repeats
self.window_size = window_size
self.text = ""
def add_text(self, new_text: str):
"""Add new text and return (is_looping, good_text_end_pos)."""
self.text += new_text
return self._check_repetition()
def _check_repetition(self):
"""Check if the recent text contains repetition loops."""
if len(self.text) < self.min_pattern_len * self.min_repeats:
return False, len(self.text)
# Check the recent window
window = self.text[-self.window_size:] if len(self.text) > self.window_size else self.text
# Method 1: Check for repeated substrings
for pattern_len in range(self.min_pattern_len, len(window) // self.min_repeats + 1):
# Get the last pattern_len characters as potential pattern
pattern = window[-pattern_len:]
# Count how many times this pattern appears at the end
count = 0
pos = len(window)
while pos >= pattern_len:
if window[pos - pattern_len:pos] == pattern:
count += 1
pos -= pattern_len
else:
break
if count >= self.min_repeats:
# Found repetition! Calculate where the good text ends
repetition_start = len(self.text) - (count * pattern_len)
# Keep one instance of the pattern (or none if it's garbage)
good_end = repetition_start + pattern_len if self._is_meaningful(pattern) else repetition_start
return True, good_end
# Method 2: Check for repeated short phrases (like "you're not, you're not")
# Look for patterns like "X, X, X" or "X X X"
words = window.split()
if len(words) >= self.min_repeats * 2:
# Check last N words for repetition
for phrase_len in range(2, 6): # 2-5 word phrases
if len(words) < phrase_len * self.min_repeats:
continue
phrase = " ".join(words[-phrase_len:])
count = 0
idx = len(words)
while idx >= phrase_len:
candidate = " ".join(words[idx - phrase_len:idx])
if candidate == phrase:
count += 1
idx -= phrase_len
else:
break
if count >= self.min_repeats:
# Calculate position in original text
repeated_text = (phrase + " ") * count
good_end = len(self.text) - len(repeated_text.rstrip()) + len(phrase)
return True, max(0, good_end)
return False, len(self.text)
def _is_meaningful(self, pattern: str) -> bool:
"""Check if pattern is meaningful content (not just garbage)."""
# Filter out patterns that are just punctuation, spaces, or very repetitive
clean = pattern.strip()
if not clean:
return False
if len(set(clean)) < 3: # Too few unique characters
return False
return True
def get_good_text(self, end_pos: int) -> str:
"""Get text up to the specified position."""
return self.text[:end_pos]
def reset(self, keep_text: str = ""):
"""Reset detector, optionally keeping some text."""
self.text = keep_text
def stream_with_recovery(
url: str,
base_messages: list,
audio_data_url: str,
prompt_text: str,
max_tokens: int = 32768,
max_retries: int = 3,
timeout: int = 12000,
debug: bool = False,
):
"""
Stream transcription with automatic recovery from repetition loops.
Args:
url: API endpoint
base_messages: Base messages (system + user with audio)
audio_data_url: The audio data URL for the request
prompt_text: The text prompt
max_tokens: Maximum tokens to generate
max_retries: Maximum recovery attempts (default 3)
timeout: Request timeout
debug: If True, show recovery debug info to stderr
Recovery strategy:
- First attempt: temperature=0.0, top_p=1.0 (greedy)
- Recovery: temperature=0.2/0.3/0.4 for retry 1/2/3, top_p=0.95
- If has complete segments: use assistant prefix
- If no complete segments: restart from scratch
- Max 3 retries, if all fail output error message
Returns:
Final transcription text
"""
import sys as _sys
def _log(msg):
"""Log to stderr only if debug."""
if debug:
print(msg, file=_sys.stderr)
detector = RepetitionDetector(
min_pattern_len=10, # At least 10 chars for a pattern
min_repeats=10, # Must repeat 10+ times
window_size=400, # Check last 400 chars (can detect 10-40 char patterns repeated 10 times)
)
accumulated_text = ""
retry_count = 0
user_safe_printed_len = 0 # Track how much we've safely shown to user (at segment boundaries)
is_recovery = False # Whether we're in recovery mode
while retry_count <= max_retries:
# Build request payload
messages = list(base_messages) # Copy base messages
# If we have accumulated text from previous attempt, add it as partial assistant response
if accumulated_text:
# Add the good content as a partial assistant message
# vLLM will continue from here
messages.append({
"role": "assistant",
"content": accumulated_text
})
# Set sampling parameters based on recovery state
if is_recovery:
# Recovery: increase temperature each retry to break loops
recovery_temp = 0.1 + 0.1 * retry_count # 0.2, 0.3, 0.4 for retry 1, 2, 3
payload = {
"model": "vibevoice",
"messages": messages,
"max_tokens": max_tokens,
"temperature": recovery_temp,
"top_p": 0.95,
"stream": True,
}
if accumulated_text:
_log(f"[RECOVERY #{retry_count}] Continuing from {len(accumulated_text)} chars with temp={recovery_temp}, top_p=0.95")
else:
_log(f"[RECOVERY #{retry_count}] Restarting from scratch with temp={recovery_temp}, top_p=0.95")
else:
# First attempt: greedy decoding
payload = {
"model": "vibevoice",
"messages": messages,
"max_tokens": max_tokens,
"temperature": 0.0,
"top_p": 1.0,
"stream": True,
}
try:
response = requests.post(url, json=payload, stream=True, timeout=timeout)
if response.status_code != 200:
_log(f"[ERROR] {response.status_code} - {response.text[:500]}")
return accumulated_text
new_text = ""
printed = "" # Track what we've already received to handle vLLM duplicates
for line in response.iter_lines():
if not line:
continue
decoded_line = line.decode('utf-8')
if not decoded_line.startswith("data: "):
continue
json_str = decoded_line[6:]
if json_str.strip() == "[DONE]":
# Successfully finished without loops
full_result = accumulated_text + new_text
# Print any remaining content that wasn't printed yet
if len(full_result) > user_safe_printed_len:
remaining = full_result[user_safe_printed_len:]
print(remaining, end='', flush=True)
print() # Final newline
return full_result
try:
data = json.loads(json_str)
delta = data['choices'][0].get('delta', {})
content = delta.get('content', '')
if content:
# vLLM/OpenAI-compatible streams may emit either
# incremental deltas OR the full accumulated text.
# Only track the newly-added part.
if content.startswith(printed):
to_add = content[len(printed):]
else:
to_add = content
if to_add:
printed += to_add
new_text += to_add
# When continuing from prefix, model may add "[" or "[{" at start
# or repeat the ending "}, " from prefix
# We need to handle these to maintain valid JSON array format
if accumulated_text and new_text:
stripped = new_text.lstrip()
# Case 1: Model added "[{" - remove the "["
if stripped.startswith("[{"):
new_text = stripped[1:]
_log("[STRIPPED leading '[' from continuation]")
# Case 2: Model added just "[" - remove it
elif stripped.startswith("["):
new_text = stripped[1:]
_log("[STRIPPED leading '[' from continuation]")
# Case 3: Model repeated "}," from prefix ending
elif stripped.startswith("},"):
new_text = stripped[2:]
_log("[STRIPPED leading '},' from continuation]")
# Case 4: Model repeated "}" from prefix ending
elif stripped.startswith("}") and not stripped.startswith("}]"):
new_text = stripped[1:]
_log("[STRIPPED leading '}' from continuation]")
# Fix malformed JSON: {"2.99,... -> {"Start":2.99,...
# This happens when model skips "Start": key
import re
malformed = re.match(r'^\{"(\d+\.?\d*),', new_text)
if malformed:
time_val = malformed.group(1)
new_text = '{"Start":' + time_val + ',' + new_text[malformed.end():]
_log(f"[FIXED malformed JSON: added Start key]")
# Check for repetition in the combined text
full_text = accumulated_text + new_text
detector.text = full_text
is_looping, good_end = detector._check_repetition()
if is_looping:
_log(f"[LOOP DETECTED at char {good_end}]")
# Use what user has already seen as prefix for retry
# user_safe_printed_len is always at a segment boundary
if user_safe_printed_len > 0:
accumulated_text = full_text[:user_safe_printed_len]
_log(f"[RETRY from user-visible content at {user_safe_printed_len}]")
else:
# No complete segment shown to user yet - restart from scratch
accumulated_text = ""
_log(f"[NO CONTENT SHOWN TO USER - restart from scratch]")
detector.reset(accumulated_text)
is_recovery = True
if debug:
print("\n[...recovering...]", end='', flush=True, file=sys.stderr)
retry_count += 1
if retry_count > max_retries:
_log(f"[MAX RETRIES REACHED]")
print("\n[Error] Transcription failed due to model output anomaly. Please try another audio or contact support.", flush=True)
return None
# Break inner loop to retry
break
else:
# No loop detected - stream content to user
# Only print up to (full_text_len - window_size) at segment boundaries
# This ensures user never sees content that might be rolled back
safe_end = max(0, len(full_text) - detector.window_size)
safe_boundary = _find_safe_print_boundary(full_text, safe_end)
if safe_boundary > user_safe_printed_len:
# Print new safe content
to_print = full_text[user_safe_printed_len:safe_boundary]
print(to_print, end='', flush=True)
user_safe_printed_len = safe_boundary
except json.JSONDecodeError:
continue
else:
# Loop completed without break (no repetition detected)
full_result = accumulated_text + new_text
# Print any remaining content that wasn't printed yet
if len(full_result) > user_safe_printed_len:
remaining = full_result[user_safe_printed_len:]
print(remaining, end='', flush=True)
print() # Final newline
return full_result
except requests.exceptions.Timeout:
_log("[TIMEOUT]")
print()
return accumulated_text
except Exception as e:
_log(f"[ERROR: {e}]")
print()
return accumulated_text
# All retries exhausted
print("\n[Error] Transcription failed due to model output anomaly. Please try another audio or contact support.", flush=True)
return None
def test_transcription_with_recovery(
audio_path: str,
output_path: str = None,
base_url: str = "http://localhost:8000",
hotwords: str = None,
debug: bool = False,
):
"""
Test ASR transcription with auto-recovery from repetition loops.
Args:
audio_path: Path to the audio file
output_path: Optional path to save transcription result
base_url: vLLM server URL
hotwords: Hotwords string (e.g., "Microsoft,Azure,VibeVoice")
debug: Show recovery debug info
"""
print(f"=" * 70)
print(f"Testing with Auto-Recovery")
print(f"=" * 70)
print(f"Input file: {audio_path}")
print(f"Hotwords: {hotwords or '(none)'}")
print()
# Handle video files: extract audio first
temp_audio_path = None
actual_audio_path = audio_path
if _is_video_file(audio_path):
print(f"🎬 Detected video file, extracting audio...")
temp_audio_path = _extract_audio_from_video(audio_path)
actual_audio_path = temp_audio_path
print(f"✅ Audio extracted to: {temp_audio_path}")
# Load audio
try:
duration = _get_duration_seconds_ffprobe(actual_audio_path)
print(f"Audio duration: {duration:.2f} seconds")
with open(actual_audio_path, "rb") as f:
audio_bytes = f.read()
audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
print(f"Audio size: {len(audio_bytes)} bytes")
except Exception as e:
print(f"❌ Error preparing audio: {e}")
# Cleanup temp file if created
if temp_audio_path and os.path.exists(temp_audio_path):
os.remove(temp_audio_path)
return
url = f"{base_url}/v1/chat/completions"
show_keys = ["Start time", "End time", "Speaker ID", "Content"]
# Build prompt with optional hotwords
if hotwords and hotwords.strip():
prompt_text = (
f"This is a {duration:.2f} seconds audio, with extra info: {hotwords.strip()}\n\n"
f"Please transcribe it with these keys: " + ", ".join(show_keys)
)
print(f"\n📝 Hotwords embedded in prompt: '{hotwords}'")
else:
prompt_text = (
f"This is a {duration:.2f} seconds audio, please transcribe it with these keys: "
+ ", ".join(show_keys)
)
print(f"\n📝 No hotwords provided")
mime = _guess_mime_type(actual_audio_path)
data_url = f"data:{mime};base64,{audio_b64}"
# Base messages (without assistant continuation)
base_messages = [
{
"role": "system",
"content": "You are a helpful assistant that transcribes audio input into text output in JSON format."
},
{
"role": "user",
"content": [
{"type": "audio_url", "audio_url": {"url": data_url}},
{"type": "text", "text": prompt_text}
]
}
]
print(f"\n{'=' * 70}")
print(f"Sending request to {url}")
print(f"{'=' * 70}")
t0 = time.time()
print("\n✅ Response received. Streaming content:\n")
print("-" * 50)
result = stream_with_recovery(
url=url,
base_messages=base_messages,
audio_data_url=data_url,
prompt_text=prompt_text,
max_tokens=32768,
max_retries=3,
debug=debug,
)
elapsed = time.time() - t0
print("-" * 50)
print("✅ [Finished]")
print(f"\n{'=' * 70}")
print(f"⏱️ Total time elapsed: {elapsed:.2f}s")
print(f"{'=' * 70}")
if result is None:
print("❌ Transcription failed")
return
print(f"📄 Final output length: {len(result)} chars")
# Optionally save result
if output_path:
with open(output_path, "w", encoding="utf-8") as f:
f.write(result)
print(f"💾 Result saved to: {output_path}")
# Cleanup temp audio file if created
if temp_audio_path and os.path.exists(temp_audio_path):
os.remove(temp_audio_path)
print(f"🗑️ Cleaned up temp file: {temp_audio_path}")
def main():
parser = argparse.ArgumentParser(
description="Test VibeVoice vLLM API with auto-recovery from repetition loops"
)
parser.add_argument(
"audio_path",
help="Path to audio file (wav, mp3, flac, etc.) or video file"
)
parser.add_argument(
"output_path",
nargs="?",
default=None,
help="Optional path to save transcription result"
)
parser.add_argument(
"--url",
default="http://localhost:8000",
help="vLLM server URL (default: http://localhost:8000)"
)
parser.add_argument(
"--hotwords",
type=str,
default=None,
help="Hotwords to improve recognition (e.g., 'Microsoft,Azure,VibeVoice')"
)
parser.add_argument(
"--debug",
action="store_true",
help="Show recovery debug info"
)
args = parser.parse_args()
# Run test
test_transcription_with_recovery(
audio_path=args.audio_path,
output_path=args.output_path,
base_url=args.url,
hotwords=args.hotwords,
debug=args.debug,
)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/tests/test_api_auto_recover.py",
"license": "MIT License",
"lines": 537,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/VibeVoice:vllm_plugin/scripts/start_server.py | #!/usr/bin/env python3
"""
VibeVoice vLLM ASR Server Launcher
One-click deployment script that handles:
1. Installing system dependencies (FFmpeg, etc.)
2. Installing VibeVoice Python package
3. Downloading model from HuggingFace
4. Generating tokenizer files
5. Starting vLLM server
Usage:
python3 start_server.py [--model MODEL_ID] [--port PORT]
"""
import argparse
import os
import subprocess
import sys
def run_command(cmd: list[str], description: str, shell: bool = False) -> None:
"""Run a command with logging."""
print(f"\n{'='*60}")
print(f" {description}")
print(f"{'='*60}\n")
if shell:
subprocess.run(cmd, shell=True, check=True)
else:
subprocess.run(cmd, check=True)
def install_system_deps() -> None:
"""Install system dependencies (FFmpeg, etc.)."""
run_command(["apt-get", "update"], "Updating package list")
run_command(
["apt-get", "install", "-y", "ffmpeg", "libsndfile1"],
"Installing FFmpeg and audio libraries"
)
def install_vibevoice() -> None:
"""Install VibeVoice Python package."""
run_command(
[sys.executable, "-m", "pip", "install", "-e", "/app[vllm]"],
"Installing VibeVoice with vLLM support"
)
def download_model(model_id: str) -> str:
"""Download model from HuggingFace using default cache."""
print(f"\n{'='*60}")
print(f" Downloading model: {model_id}")
print(f"{'='*60}\n")
import warnings
from huggingface_hub import snapshot_download
# Suppress deprecation warnings from huggingface_hub
with warnings.catch_warnings():
warnings.simplefilter("ignore")
model_path = snapshot_download(model_id)
print(f"\n{'='*60}")
print(f" ✅ Model downloaded successfully!")
print(f" 📁 Path: {model_path}")
print(f"{'='*60}\n")
return model_path
def generate_tokenizer(model_path: str) -> None:
"""Generate tokenizer files for the model."""
run_command(
[sys.executable, "-m", "vllm_plugin.tools.generate_tokenizer_files",
"--output", model_path],
"Generating tokenizer files"
)
def start_vllm_server(model_path: str, port: int) -> None:
"""Start vLLM server (replaces current process)."""
print(f"\n{'='*60}")
print(f" Starting vLLM server on port {port}")
print(f"{'='*60}\n")
vllm_cmd = [
"vllm", "serve", model_path,
"--served-model-name", "vibevoice",
"--trust-remote-code",
"--dtype", "bfloat16",
"--max-num-seqs", "64",
"--max-model-len", "65536",
# "--max-num-batched-tokens", "32768",
"--gpu-memory-utilization", "0.8",
# "--enforce-eager",
"--no-enable-prefix-caching",
"--enable-chunked-prefill",
"--chat-template-content-format", "openai",
"--tensor-parallel-size", "1",
"--allowed-local-media-path", "/app",
"--port", str(port),
]
os.execvp("vllm", vllm_cmd)
def main():
parser = argparse.ArgumentParser(
description="VibeVoice vLLM ASR Server - One-Click Deployment",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Start with default settings
python3 start_server.py
# Use custom port
python3 start_server.py --port 8080
# Skip dependency installation (if already installed)
python3 start_server.py --skip-deps
"""
)
parser.add_argument(
"--model", "-m",
default="microsoft/VibeVoice-ASR",
help="HuggingFace model ID (default: microsoft/VibeVoice-ASR)"
)
parser.add_argument(
"--port", "-p",
type=int,
default=8000,
help="Server port (default: 8000)"
)
parser.add_argument(
"--skip-deps",
action="store_true",
help="Skip installing system dependencies"
)
parser.add_argument(
"--skip-tokenizer",
action="store_true",
help="Skip generating tokenizer files"
)
args = parser.parse_args()
print("\n" + "="*60)
print(" VibeVoice vLLM ASR Server - One-Click Deployment")
print("="*60)
# Step 1: Install system dependencies
if not args.skip_deps:
install_system_deps()
# Step 2: Install VibeVoice
install_vibevoice()
# Step 3: Download model
model_path = download_model(args.model)
# Step 4: Generate tokenizer files
if not args.skip_tokenizer:
generate_tokenizer(model_path)
# Step 5: Start vLLM server
start_vllm_server(model_path, args.port)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/scripts/start_server.py",
"license": "MIT License",
"lines": 137,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/VibeVoice:vllm_plugin/inputs.py | """Audio input mapper for vLLM multimodal pipeline.
This module handles audio data loading and preprocessing for VibeVoice ASR inference.
It converts various audio input formats (path, bytes, numpy array) into tensors
that can be processed by the VibeVoice model.
"""
import torch
import numpy as np
from typing import Union, List
from vllm.multimodal.inputs import MultiModalInputs
from vibevoice.processor.audio_utils import load_audio_use_ffmpeg, load_audio_bytes_use_ffmpeg, AudioNormalizer
def load_audio(audio_path: str, target_sr: int = 24000) -> np.ndarray:
"""Load and normalize audio from file path.
Args:
audio_path: Path to audio file
target_sr: Target sample rate (default 24kHz for VibeVoice)
Returns:
Normalized audio waveform as numpy array
"""
# Load with FFmpeg (handles various formats)
audio, sr = load_audio_use_ffmpeg(audio_path, resample=True, target_sr=target_sr)
# Normalize audio
normalizer = AudioNormalizer()
audio = normalizer(audio)
return audio
def vibevoice_audio_input_mapper(ctx, data: Union[str, bytes, np.ndarray, List[str]]) -> MultiModalInputs:
"""Map audio input data to vLLM MultiModalInputs format.
This function is registered as the input mapper for VibeVoice audio processing.
It handles multiple input formats and converts them to normalized tensors.
Args:
ctx: vLLM context (unused)
data: Audio data in one of these formats:
- str: Path to audio file
- bytes: Raw audio bytes (any format FFmpeg supports)
- np.ndarray: Pre-loaded audio waveform
- List[str]: List of audio paths (only first is used)
Returns:
MultiModalInputs containing:
- audio: Audio tensor (float32)
- audio_length: Length of audio in samples
"""
# Handle list input (take first item)
if isinstance(data, list):
data = data[0]
audio_waveform = None
if isinstance(data, str):
# Load from file path
audio_waveform = load_audio(data)
elif isinstance(data, bytes):
# Decode bytes directly via ffmpeg stdin pipe to avoid temp-file IO
audio_waveform, _sr = load_audio_bytes_use_ffmpeg(data, resample=True, target_sr=24000)
normalizer = AudioNormalizer()
audio_waveform = normalizer(audio_waveform)
elif isinstance(data, np.ndarray):
# Already loaded numpy array
audio_waveform = data
else:
raise ValueError(f"Unsupported audio data type: {type(data)}")
# Convert to tensor
audio_tensor = torch.from_numpy(audio_waveform).float()
audio_length = audio_tensor.shape[0]
return MultiModalInputs({
"audio": audio_tensor,
"audio_length": audio_length
})
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/inputs.py",
"license": "MIT License",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
microsoft/VibeVoice:vllm_plugin/model.py | """
VibeVoice vLLM Plugin Model - Native Multimodal Integration
This module implements the VibeVoice ASR model with full vLLM multimodal registry
integration for speech-to-text inference.
"""
from typing import List, Optional, Tuple, Union, Dict, Any, Iterable, Mapping, Sequence
import os
import torch
import torch.nn as nn
import numpy as np
import base64
# ============================================================================
# Audio Loading: FFmpeg-based AudioMediaIO
# ============================================================================
# VibeVoice uses FFmpeg for audio decoding to ensure consistent behavior
# across different audio formats (MP3, WAV, FLAC, etc.).
from vibevoice.processor.audio_utils import load_audio_use_ffmpeg, load_audio_bytes_use_ffmpeg, AudioNormalizer
def _ffmpeg_load_bytes(data: bytes) -> tuple[np.ndarray, int]:
"""Load audio bytes using FFmpeg via stdin-pipe decoding.
Returns:
Tuple of (audio_waveform, sample_rate). Sample rate is always 24000.
"""
audio, sr = load_audio_bytes_use_ffmpeg(data, resample=True, target_sr=24000)
normalizer = AudioNormalizer()
audio = normalizer(audio)
return audio, sr
def _ffmpeg_load_file(filepath) -> tuple[np.ndarray, int]:
"""Load audio file using FFmpeg.
Returns:
Tuple of (audio_waveform, sample_rate). Sample rate is always 24000.
"""
audio, sr = load_audio_use_ffmpeg(str(filepath), resample=True, target_sr=24000)
normalizer = AudioNormalizer()
audio = normalizer(audio)
return audio, sr
# Register FFmpeg-based audio loader
try:
# Try new location (vLLM >= 0.6.x)
from vllm.multimodal.media.audio import AudioMediaIO as _OriginalAudioMediaIO
except ImportError:
# Fall back to old location (vLLM < 0.6.x)
import vllm.multimodal.audio as _vllm_audio_module
_OriginalAudioMediaIO = _vllm_audio_module.AudioMediaIO
class _PatchedAudioMediaIO(_OriginalAudioMediaIO):
"""AudioMediaIO implementation using FFmpeg for audio decoding."""
def load_bytes(self, data: bytes) -> tuple[np.ndarray, int]:
return _ffmpeg_load_bytes(data)
def load_base64(self, media_type: str, data: str) -> tuple[np.ndarray, int]:
return _ffmpeg_load_bytes(base64.b64decode(data))
def load_file(self, filepath) -> tuple[np.ndarray, int]:
return _ffmpeg_load_file(filepath)
# Replace globally
try:
# For new vLLM versions
import vllm.multimodal.media.audio as _vllm_audio_module
_vllm_audio_module.AudioMediaIO = _PatchedAudioMediaIO
except ImportError:
# For old vLLM versions
import vllm.multimodal.audio as _vllm_audio_module
_vllm_audio_module.AudioMediaIO = _PatchedAudioMediaIO
# Also patch in utils module where it's imported
try:
import vllm.multimodal.utils as _vllm_utils_module
_vllm_utils_module.AudioMediaIO = _PatchedAudioMediaIO
except (ImportError, AttributeError):
# AudioMediaIO might not be imported in utils in newer versions
pass
# ============================================================================
from transformers import BatchFeature
from transformers.models.whisper import WhisperFeatureExtractor
from vllm.config import VllmConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.parse import MultiModalDataParser
from vllm.sequence import IntermediateTensors
from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP, MultiModalEmbeddings
from vllm.model_executor.models.utils import (
init_vllm_registered_model,
maybe_prefix,
AutoWeightsLoader,
WeightsMapper,
)
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
from vllm.multimodal.processing import (
BaseMultiModalProcessor,
BaseProcessingInfo,
PromptReplacement,
PromptUpdate,
PromptUpdateDetails,
)
try:
# Try new location (vLLM >= 0.6.x)
from vllm.multimodal.processing import BaseDummyInputsBuilder, ProcessorInputs
except ImportError:
# Fall back to old location (vLLM < 0.6.x)
try:
from vllm.multimodal.profiling import BaseDummyInputsBuilder, ProcessorInputs
except ImportError:
# If neither location works, try individual imports
from vllm.multimodal.processing.dummy_inputs import BaseDummyInputsBuilder
from vllm.multimodal.processing.inputs import ProcessorInputs
# Import VibeVoice components
from vibevoice.modular.modular_vibevoice_tokenizer import (
VibeVoiceAcousticTokenizerModel,
VibeVoiceSemanticTokenizerModel,
VibeVoiceTokenizerStreamingCache,
VibeVoiceTokenizerEncoderOutput,
)
from vibevoice.modular.configuration_vibevoice import (
VibeVoiceAcousticTokenizerConfig,
VibeVoiceSemanticTokenizerConfig,
)
class SpeechConnector(nn.Module):
"""Projects speech features to language model hidden dimension.
Architecture: fc1 -> RMSNorm -> fc2 (no activation function)
"""
def __init__(self, input_dim: int, output_dim: int):
super().__init__()
self.fc1 = nn.Linear(input_dim, output_dim)
self.norm = LlamaRMSNorm(output_dim, eps=1e-6)
self.fc2 = nn.Linear(output_dim, output_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.fc1(x)
x = self.norm(x)
x = self.fc2(x)
return x
class LlamaRMSNorm(nn.Module):
"""RMSNorm layer used in SpeechConnector."""
def __init__(self, hidden_size: int, eps: float = 1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
class VibeVoiceAudioEncoder(nn.Module):
"""
VibeVoice Audio Encoder module.
Encapsulates Acoustic/Semantic VAE Tokenizers and projection Connectors.
Converts raw audio waveforms into embeddings compatible with the language model.
Features:
- Streaming support for long audio (>60s by default)
- Configurable dtype for numerical precision
- Supports both sampling and deterministic (mean) modes
"""
def __init__(self, config):
super().__init__()
self.config = config
import sys
def get_cfg(obj, key, default=None):
if isinstance(obj, dict):
return obj.get(key, default)
return getattr(obj, key, default)
self.acoustic_vae_dim = get_cfg(config, "acoustic_vae_dim", 64)
self.semantic_vae_dim = get_cfg(config, "semantic_vae_dim", 128)
decoder_config = get_cfg(config, "decoder_config")
text_config = get_cfg(config, "text_config")
target_hidden_size = None
if decoder_config is not None:
target_hidden_size = get_cfg(decoder_config, "hidden_size")
if target_hidden_size is None and text_config is not None:
target_hidden_size = get_cfg(text_config, "hidden_size")
if target_hidden_size is None:
target_hidden_size = get_cfg(config, "hidden_size")
if target_hidden_size is None:
print("[VibeVoice] WARN: Could not find hidden_size in config! Defaulting to 3584 (7B).", file=sys.stderr)
self.hidden_size = 3584
else:
self.hidden_size = target_hidden_size
ac_cfg = get_cfg(config, "acoustic_tokenizer_config")
sc_cfg = get_cfg(config, "semantic_tokenizer_config")
if ac_cfg is None or sc_cfg is None:
raise ValueError("Missing acoustic/semantic tokenizer config in model config")
# Handle both dict and already-constructed config objects
if isinstance(ac_cfg, VibeVoiceAcousticTokenizerConfig):
acoustic_config = ac_cfg
elif isinstance(ac_cfg, dict):
acoustic_config = VibeVoiceAcousticTokenizerConfig(**ac_cfg)
else:
raise TypeError(f"acoustic_tokenizer_config has unexpected type: {type(ac_cfg)}")
if isinstance(sc_cfg, VibeVoiceSemanticTokenizerConfig):
semantic_config = sc_cfg
elif isinstance(sc_cfg, dict):
semantic_config = VibeVoiceSemanticTokenizerConfig(**sc_cfg)
else:
raise TypeError(f"semantic_tokenizer_config has unexpected type: {type(sc_cfg)}")
# Tokenizers use float32 for numerical precision
self.acoustic_tokenizer = VibeVoiceAcousticTokenizerModel(acoustic_config)
self.semantic_tokenizer = VibeVoiceSemanticTokenizerModel(semantic_config)
# Get audio encoder dtype from config (defaults to float32 for precision)
root_torch_dtype = get_cfg(config, "torch_dtype", None)
if root_torch_dtype is not None:
if isinstance(root_torch_dtype, str):
self._audio_encoder_dtype = getattr(torch, root_torch_dtype)
else:
self._audio_encoder_dtype = root_torch_dtype
else:
self._audio_encoder_dtype = torch.float32
self.acoustic_connector = SpeechConnector(self.acoustic_vae_dim, self.hidden_size)
self.semantic_connector = SpeechConnector(self.semantic_vae_dim, self.hidden_size)
self.compress_ratio = get_cfg(config, "speech_tok_compress_ratio", 3200)
# Streaming controls
self.sample_rate = get_cfg(config, "target_sample_rate", 24000)
# Default to True (per requirement): segment + cache inside one forward call.
self.enable_streaming = get_cfg(config, "enable_streaming", True)
self.streaming_segment_duration = get_cfg(config, "streaming_segment_duration", 60.0)
# Control whether to use sample() or .mean for acoustic tokens
# Default: use sample() for training-consistent behavior
# Set VIBEVOICE_USE_MEAN=1 for deterministic output
use_mean_env = os.getenv("VIBEVOICE_USE_MEAN", "").strip().lower()
self.use_sample = use_mean_env not in ("1", "true", "yes")
# Language model dtype (set by VibeVoiceForCausalLM.__init__)
# This is the dtype that audio embeddings will be converted to before
# being passed to the language model. Defaults to bfloat16.
self._lm_dtype: torch.dtype = torch.bfloat16
def _ensure_audio_encoder_dtype(self):
"""Ensure all audio encoder components use the correct dtype from config.
vLLM may convert weights to a different dtype (e.g., bfloat16) during loading.
This method converts audio encoder components back to the config-specified dtype
(typically float32) for numerical precision during audio encoding.
"""
import sys
target_dtype = self._audio_encoder_dtype
# Check and convert acoustic_tokenizer
try:
acoustic_dtype = next(self.acoustic_tokenizer.parameters()).dtype
if acoustic_dtype != target_dtype:
self.acoustic_tokenizer = self.acoustic_tokenizer.to(dtype=target_dtype)
print(f"[VibeVoice] Converted acoustic_tokenizer to {target_dtype} (was {acoustic_dtype})", file=sys.stderr)
except StopIteration:
pass
# Check and convert semantic_tokenizer
try:
semantic_dtype = next(self.semantic_tokenizer.parameters()).dtype
if semantic_dtype != target_dtype:
self.semantic_tokenizer = self.semantic_tokenizer.to(dtype=target_dtype)
print(f"[VibeVoice] Converted semantic_tokenizer to {target_dtype} (was {semantic_dtype})", file=sys.stderr)
except StopIteration:
pass
# Check and convert acoustic_connector
try:
ac_conn_dtype = next(self.acoustic_connector.parameters()).dtype
if ac_conn_dtype != target_dtype:
self.acoustic_connector = self.acoustic_connector.to(dtype=target_dtype)
print(f"[VibeVoice] Converted acoustic_connector to {target_dtype} (was {ac_conn_dtype})", file=sys.stderr)
except StopIteration:
pass
# Check and convert semantic_connector
try:
sc_conn_dtype = next(self.semantic_connector.parameters()).dtype
if sc_conn_dtype != target_dtype:
self.semantic_connector = self.semantic_connector.to(dtype=target_dtype)
print(f"[VibeVoice] Converted semantic_connector to {target_dtype} (was {sc_conn_dtype})", file=sys.stderr)
except StopIteration:
pass
def forward(
self,
audio: torch.Tensor,
*,
use_streaming: bool = True,
segment_duration_s: Optional[float] = None,
use_sample: Optional[bool] = None,
) -> torch.Tensor:
"""Encode audio with optional streaming for long clips.
Args:
audio: Input audio tensor [B, T] or [T]
use_streaming: Whether to enable segmented encoding for long audio
segment_duration_s: Segment length in seconds (defaults to 60s)
use_sample: If True, use sampling for acoustic tokens; if False, use mean
Defaults to self.use_sample (controlled by VIBEVOICE_USE_MEAN env var)
Returns:
Audio embeddings tensor compatible with the language model
"""
# Ensure audio encoder components use correct dtype
self._ensure_audio_encoder_dtype()
# Audio input should match the audio encoder dtype
audio = audio.to(dtype=self._audio_encoder_dtype)
if audio.ndim == 1:
audio = audio.unsqueeze(0)
# Resolve streaming options
segment_duration = segment_duration_s or self.streaming_segment_duration
sample_rate = self.sample_rate
total_samples = audio.shape[-1]
segment_samples = int(segment_duration * sample_rate)
use_streaming = use_streaming and self.enable_streaming and total_samples > segment_samples
# Resolve use_sample flag
if use_sample is None:
use_sample = self.use_sample
# Keep encoding in inference mode to avoid autograd build-up
with torch.no_grad():
if not use_streaming:
acoustic_input = audio.unsqueeze(1)
acoustic_out = self.acoustic_tokenizer.encode(acoustic_input)
# Use sample() or .mean based on use_sample flag
if use_sample:
acoustic_tokens = acoustic_out.sample(
dist_type=self.acoustic_tokenizer.std_dist_type
)[0]
else:
acoustic_tokens = acoustic_out.mean
# Connector is now float32, no conversion needed
acoustic_embeds = self.acoustic_connector(acoustic_tokens)
semantic_out = self.semantic_tokenizer.encode(acoustic_input)
# Semantic always uses .mean for consistency
semantic_tokens = semantic_out.mean
# Connector is now float32, no conversion needed
semantic_embeds = self.semantic_connector(semantic_tokens)
else:
# ==========================================
# Streaming path (Retained for future use)
# ==========================================
acoustic_cache = VibeVoiceTokenizerStreamingCache()
semantic_cache = VibeVoiceTokenizerStreamingCache()
acoustic_mean_segments = []
semantic_mean_segments = []
batch_size = audio.shape[0]
sample_indices = torch.arange(batch_size, device=audio.device)
def _iter_segments(total_length: int, segment_length: int):
for start in range(0, total_length, segment_length):
end = min(start + segment_length, total_length)
if end > start:
yield start, end
segments = list(_iter_segments(total_samples, segment_samples))
num_segments = len(segments)
for seg_idx, (start, end) in enumerate(segments):
chunk = audio[:, start:end].contiguous()
if chunk.numel() == 0:
continue
# Check if this is the final segment
is_final = (seg_idx == num_segments - 1)
# --- Acoustic Encode ---
acoustic_enc_out = self.acoustic_tokenizer.encode(
chunk.unsqueeze(1),
cache=acoustic_cache,
sample_indices=sample_indices,
use_cache=True,
is_final_chunk=is_final,
)
acoustic_mean_segments.append(acoustic_enc_out.mean)
# --- Semantic Encode ---
semantic_enc_out = self.semantic_tokenizer.encode(
chunk.unsqueeze(1),
cache=semantic_cache,
sample_indices=sample_indices,
use_cache=True,
is_final_chunk=is_final,
)
semantic_mean_segments.append(semantic_enc_out.mean)
# Concatenate sequence outputs (Acoustic)
if len(acoustic_mean_segments) == 0:
acoustic_mean_full = torch.zeros(
(batch_size, 0, self.acoustic_vae_dim),
device=audio.device,
dtype=self._audio_encoder_dtype # Use config dtype
)
else:
acoustic_mean_full = torch.cat(acoustic_mean_segments, dim=1).contiguous()
# Get acoustic tokens based on use_sample flag
acoustic_enc_full = VibeVoiceTokenizerEncoderOutput(
mean=acoustic_mean_full,
std=self.acoustic_tokenizer.fix_std,
)
if use_sample:
acoustic_tokens = acoustic_enc_full.sample(
dist_type=self.acoustic_tokenizer.std_dist_type
)[0]
else:
acoustic_tokens = acoustic_enc_full.mean
# Connector uses same dtype as tokenizer
acoustic_embeds = self.acoustic_connector(acoustic_tokens)
# Concatenate sequence outputs (Semantic)
if len(semantic_mean_segments) == 0:
semantic_tokens = torch.zeros(
(batch_size, 0, self.semantic_vae_dim),
device=audio.device,
dtype=self._audio_encoder_dtype # Use config dtype
)
else:
semantic_tokens = torch.cat(semantic_mean_segments, dim=1).contiguous()
# Connector uses same dtype as tokenizer
semantic_embeds = self.semantic_connector(semantic_tokens)
# Combine acoustic and semantic embeddings
combined_embeds = acoustic_embeds + semantic_embeds
# Convert to language model dtype for compatibility
# Audio encoder uses config.torch_dtype (typically float32) for numerical precision,
# but LM expects the dtype specified by vLLM's --dtype flag (e.g., bfloat16, float16)
combined_embeds = combined_embeds.to(dtype=self._lm_dtype)
return combined_embeds
# ============================================================================
# vLLM Multimodal Processing Infrastructure
# ============================================================================
class VibeVoiceProcessingInfo(BaseProcessingInfo):
"""Processing info for VibeVoice multimodal model."""
def get_hf_config(self):
return self.ctx.get_hf_config()
def get_feature_extractor(self, **kwargs) -> WhisperFeatureExtractor:
"""
Get a WhisperFeatureExtractor for vLLM profiling compatibility.
IMPORTANT: This is NOT used in actual inference!
VibeVoice uses its own acoustic/semantic VAE tokenizers operating on
raw 24kHz waveforms, NOT Whisper mel spectrograms.
This feature extractor exists only to satisfy vLLM's multimodal
profiling infrastructure which may query audio parameters like
sampling_rate and chunk_length for memory estimation.
"""
# Read config from preprocessor_config.json if available
import json
import os
model_path = self.ctx.model_config.model
preprocessor_path = os.path.join(model_path, "preprocessor_config.json")
# Default values: keep a coherent (sr, hop) pair.
# VibeVoice runs at 24kHz in this repo (see demo/asr_transcribe_file.py).
config = {
"sampling_rate": 24000,
"feature_size": 128,
# 10ms hop at 24kHz
"hop_length": 240,
"chunk_length": 30,
"n_fft": 400,
"padding_value": 0.0,
}
# Try to load from config file
if os.path.exists(preprocessor_path):
try:
with open(preprocessor_path, "r") as f:
file_config = json.load(f)
config.update({k: file_config[k] for k in config.keys() if k in file_config})
except Exception:
pass # Use defaults
return WhisperFeatureExtractor(
feature_size=config["feature_size"],
sampling_rate=config["sampling_rate"],
hop_length=config["hop_length"],
chunk_length=config["chunk_length"],
n_fft=config["n_fft"],
padding_value=config["padding_value"],
)
def get_audio_token_info(self) -> dict:
"""
Get audio special tokens and their IDs.
Returns dict with:
audio_token, audio_bos_token, audio_eos_token,
audio_token_id, audio_bos_id, audio_eos_id
"""
tokenizer = self.get_tokenizer()
vocab = tokenizer.get_vocab()
# VibeVoice special tokens
tokens = {
"audio_token": "<|AUDIO|>",
"audio_bos_token": "<|audio_bos|>",
"audio_eos_token": "<|audio_eos|>",
}
# Get IDs
tokens["audio_token_id"] = vocab.get(tokens["audio_token"])
tokens["audio_bos_id"] = vocab.get(tokens["audio_bos_token"])
tokens["audio_eos_id"] = vocab.get(tokens["audio_eos_token"])
return tokens
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
return {"audio": 1}
def get_mm_max_tokens_per_item(
self,
seq_len: int,
mm_counts: Mapping[str, int],
) -> Mapping[str, int]:
"""Return the maximum number of audio tokens per item.
This tells vLLM's scheduler the upper bound so that
``encoder_compute_budget`` is large enough for any audio length
the model can handle, preventing the silent scheduling deadlock
described in docs/max_num_batched_tokens_issue.md.
Formula: audio_tokens = ceil(audio_samples / compress_ratio) + 3
where +3 accounts for speech_start, speech_end, and newline tokens.
The max audio samples is bounded by seq_len (the model's context
window cannot hold more tokens than that).
"""
hf_config = self.get_hf_config()
def _cfg(key: str, default):
if isinstance(hf_config, dict):
return hf_config.get(key, default)
return getattr(hf_config, key, default)
compress_ratio = int(_cfg("speech_tok_compress_ratio", 3200))
sample_rate = int(_cfg("target_sample_rate", 24000))
# Upper bound: 61-minute audio at 24 kHz
max_audio_samples = 61 * 60 * sample_rate # 88,464,000
max_audio_tokens = int(np.ceil(max_audio_samples / compress_ratio)) + 3
# Cannot exceed the model's context window
max_audio_tokens = min(max_audio_tokens, seq_len)
return {"audio": max_audio_tokens}
class VibeVoiceDummyInputsBuilder(BaseDummyInputsBuilder[VibeVoiceProcessingInfo]):
"""
Build dummy inputs for multimodal profiling.
vLLM uses dummy inputs to:
1. Measure peak GPU activation memory → determine KV cache capacity
2. Warm up CUDA graphs
The dummy audio length must be consistent with ``get_mm_max_tokens_per_item``
so that the memory estimate covers the worst-case (longest audio) scenario.
"""
def _get_max_audio_samples(self, seq_len: int) -> int:
"""Compute maximum audio samples consistent with ``get_mm_max_tokens_per_item``.
Uses the same formula: max_tokens = min(ceil(61min * sr / ratio) + 3, seq_len),
then converts back to samples.
"""
hf_config = self.info.get_hf_config()
def _cfg(key: str, default):
if isinstance(hf_config, dict):
return hf_config.get(key, default)
return getattr(hf_config, key, default)
compress_ratio = int(_cfg("speech_tok_compress_ratio", 3200))
sample_rate = int(_cfg("target_sample_rate", 24000))
# Upper bound: 61-minute audio at 24 kHz
max_hour_samples = 61 * 60 * sample_rate # 88,464,000
max_tokens_from_audio = int(np.ceil(max_hour_samples / compress_ratio)) + 3
# Cannot exceed model context window
max_tokens = min(max_tokens_from_audio, seq_len)
# Convert tokens back to samples
return max_tokens * compress_ratio
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
num_audios = mm_counts.get("audio", 0)
if num_audios <= 0:
return ""
token_info = self.info.get_audio_token_info()
audio_token = token_info["audio_token"]
return audio_token * num_audios
def get_dummy_mm_data(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, Any] | None = None,
) -> Dict[str, Any]:
"""Generate dummy audio data for profiling.
The audio length is derived from ``seq_len`` so that profiling
accurately measures memory for the longest audio the model can handle.
Supports ``AudioDummyOptions.length`` override for faster startup.
"""
num_audios = mm_counts.get("audio", 0)
max_audio_len = self._get_max_audio_samples(seq_len)
audio_overrides = mm_options.get("audio") if mm_options else None
return {
"audio": self._get_dummy_audios(
length=max_audio_len,
num_audios=num_audios,
overrides=audio_overrides,
)
}
def get_dummy_processor_inputs(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, Any] | None = None,
) -> ProcessorInputs:
"""Build ProcessorInputs for dummy profiling."""
return ProcessorInputs(
prompt=self.get_dummy_text(mm_counts),
mm_data=self.get_dummy_mm_data(seq_len, mm_counts, mm_options),
)
def _vibevoice_field_config(hf_inputs: Mapping[str, torch.Tensor]):
"""Map HF processor output keys to audio modality.
Returns a config dict that tells vLLM how to batch multimodal data.
"""
# Always define the config for all fields we use
# Even if the field isn't in hf_inputs, vLLM needs to know how to batch it
config = {
# These are our custom fields for VibeVoice
"raw_audio": MultiModalFieldConfig.batched("audio"),
"raw_audio_lengths": MultiModalFieldConfig.batched("audio"),
"salt": MultiModalFieldConfig.batched("audio"),
}
# Add optional Whisper features if present
if "input_features" in hf_inputs:
config["input_features"] = MultiModalFieldConfig.batched("audio")
if "feature_attention_mask" in hf_inputs:
config["feature_attention_mask"] = MultiModalFieldConfig.batched("audio")
return config
class VibeVoiceMultiModalProcessor(BaseMultiModalProcessor[VibeVoiceProcessingInfo]):
"""
Multimodal processor for VibeVoice.
Handles the conversion of raw audio inputs to model-ready features,
and manages the prompt token replacement for audio placeholders.
"""
def _get_data_parser(self) -> MultiModalDataParser:
"""Create a data parser with the correct target sample rate (24kHz)."""
# VibeVoice requires 24kHz, not 16kHz (Whisper default)
target_sr = 24000
return MultiModalDataParser(target_sr=target_sr)
def _call_hf_processor(
self,
prompt: str,
mm_data: Mapping[str, object],
mm_kwargs: Mapping[str, object],
tok_kwargs: Mapping[str, object],
) -> BatchFeature:
"""
Process prompt and audio for vLLM multimodal pipeline.
We intentionally do NOT run a HF processor that would pre-expand
`<|AUDIO|>` inside this method. Instead we:
1) Tokenize the prompt as-is (so `<|AUDIO|>` stays a single token)
2) Store raw audio tensors for `embed_multimodal` to encode later
3) Let vLLM call `_get_prompt_updates` to expand the single `<|AUDIO|>`
into the full ASR format: [speech_start] + N*[speech_pad] + [speech_end] + [\\n]
"""
# Handle the case where 'audios' key is used (transformers deprecation)
mm_data = dict(mm_data) # Make a mutable copy
audios = mm_data.pop("audios", None)
if audios is not None and "audio" not in mm_data:
mm_data["audio"] = audios
# Text-only input handling
if not mm_data.get("audio"):
prompt_ids = self.info.get_tokenizer().encode(prompt)
prompt_ids = self._apply_hf_processor_tokens_only(prompt_ids)
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
# Get raw audio data
raw_audio_list = mm_data.get("audio")
if isinstance(raw_audio_list, np.ndarray):
raw_audio_list = [raw_audio_list]
elif not isinstance(raw_audio_list, list):
raw_audio_list = list(raw_audio_list)
# Tokenize prompt directly to preserve <|AUDIO|> as a single token
# vLLM will expand it via _get_prompt_updates
tokenizer = self.info.get_tokenizer()
prompt_ids = tokenizer.encode(prompt, add_special_tokens=False)
prompt_ids = self._apply_hf_processor_tokens_only(prompt_ids)
# Create result with input_ids
result = BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
# Add raw audio tensors for VibeVoice encoder
# Stack into a single tensor for vLLM's batched field config
max_len = max(len(a) for a in raw_audio_list)
raw_audio_tensors = []
audio_lengths = []
for audio in raw_audio_list:
audio_len = len(audio)
audio_lengths.append(audio_len)
if audio_len < max_len:
audio = np.pad(audio, (0, max_len - audio_len), mode='constant')
raw_audio_tensors.append(torch.from_numpy(audio).float())
# Stack into [num_audios, max_len] tensor
stacked_audio = torch.stack(raw_audio_tensors, dim=0) # Shape: [num_audios, max_len]
result["raw_audio"] = stacked_audio
# Convert lengths to tensor as well
result["raw_audio_lengths"] = torch.tensor(audio_lengths, dtype=torch.long)
# Add a random salt to ensure unique hash and bypass cache
import uuid
# Use a random integer for salt
salt_val = hash(str(uuid.uuid4())) % 100000
result["salt"] = torch.tensor([salt_val], dtype=torch.long).expand(len(raw_audio_list))
return result
def _hf_processor_applies_updates(
self,
prompt_text: str,
mm_items,
hf_processor_mm_kwargs: Mapping[str, object],
tokenization_kwargs: Mapping[str, object],
) -> bool:
"""Return whether the HF processor applies prompt updates.
Returns False because we handle token expansion via _get_prompt_updates.
"""
return False
def _get_mm_fields_config(
self,
hf_inputs: BatchFeature,
hf_processor_mm_kwargs: Mapping[str, object],
) -> Mapping[str, MultiModalFieldConfig]:
"""Configure which HF output fields map to which modality."""
return _vibevoice_field_config(hf_inputs)
def _get_prompt_updates(
self,
mm_items,
hf_processor_mm_kwargs: Mapping[str, object],
out_mm_kwargs: MultiModalKwargsItems,
) -> Sequence[PromptUpdate]:
"""
Define how to replace the audio placeholder in the prompt.
vLLM's OpenAI multimodal parsing inserts the model placeholder string
from `get_placeholder_str` (here: `<|AUDIO|>`) into the conversation.
We expand that single token into N repeated `<|AUDIO|>` tokens, where N
is derived from waveform length and `speech_tok_compress_ratio`.
"""
token_info = self.info.get_audio_token_info()
audio_token = token_info["audio_token"]
audio_token_id = token_info["audio_token_id"]
audio_bos_id = token_info.get("audio_bos_id")
audio_eos_id = token_info.get("audio_eos_id")
tokenizer = self.info.get_tokenizer()
vocab = tokenizer.get_vocab()
def _tok_id(name: str) -> int | None:
return vocab.get(name)
# Look up speech token IDs from vocabulary
# These tokens mark the start/end of audio embeddings in the prompt
speech_start_id = (
_tok_id("<|object_ref_start|>")
or getattr(tokenizer, "speech_start_id", None)
or _tok_id("<|speech_start|>")
)
speech_end_id = (
_tok_id("<|object_ref_end|>")
or getattr(tokenizer, "speech_end_id", None)
or _tok_id("<|speech_end|>")
)
speech_pad_id = (
_tok_id("<|box_start|>")
or getattr(tokenizer, "speech_pad_id", None)
or _tok_id("<|speech_pad|>")
)
if audio_token_id is None:
return []
# Get raw audio lengths (in samples, after resampling to 24kHz) from our stored data
out_mm_data = out_mm_kwargs.get_data()
raw_audio_lengths = out_mm_data.get("raw_audio_lengths", [])
# Fetch defaults from model config when available (falls back to 3200)
hf_config = self.info.get_hf_config()
if isinstance(hf_config, dict):
compress_ratio = int(hf_config.get("speech_tok_compress_ratio", 3200))
else:
compress_ratio = int(getattr(hf_config, "speech_tok_compress_ratio", 3200))
def _to_int_len(x) -> int:
if x is None:
return 0
if isinstance(x, torch.Tensor):
# Accept 0-dim or 1-dim scalar-like tensors
if x.numel() == 1:
return int(x.item())
# If a full tensor is passed accidentally, fall back to its length
return int(x.shape[0])
return int(x)
def get_replacement(item_idx: int):
if raw_audio_lengths and item_idx < len(raw_audio_lengths):
audio_len = _to_int_len(raw_audio_lengths[item_idx])
num_features = max(1, int(np.ceil(audio_len / compress_ratio)))
else:
# Fallback: estimate for 30 second audio at 24kHz
num_features = int(np.ceil(30 * 24000 / compress_ratio))
if num_features == 0:
raise ValueError(
f"Audio at index {item_idx} is too short to be represented"
)
# Build replacement token sequence:
# <|speech_start|> + N * <|speech_pad|> + <|speech_end|> + \n
# The newline is important for correct prompt structure.
newline_id = 198 # '\n' token
if speech_start_id is not None and speech_pad_id is not None and speech_end_id is not None:
embed_id = int(speech_pad_id)
replacement_ids = [int(speech_start_id)] + [embed_id] * num_features + [int(speech_end_id), newline_id]
# Fallback: add audio BOS/EOS boundaries around repeated <|AUDIO|>.
elif audio_bos_id is not None and audio_eos_id is not None:
embed_id = int(audio_token_id)
replacement_ids = [int(audio_bos_id)] + [embed_id] * num_features + [int(audio_eos_id)]
else:
embed_id = int(audio_token_id)
replacement_ids = [embed_id] * num_features
return PromptUpdateDetails.select_token_id(
replacement_ids,
embed_token_id=int(embed_id),
)
return [
PromptReplacement(
modality="audio",
# Keep string placeholder matching for maximum vLLM compatibility.
target=audio_token,
replacement=get_replacement,
)
]
# ============================================================================
# Main Model Class
# ============================================================================
@MULTIMODAL_REGISTRY.register_processor(
VibeVoiceMultiModalProcessor,
info=VibeVoiceProcessingInfo,
dummy_inputs=VibeVoiceDummyInputsBuilder,
)
class VibeVoiceForCausalLM(nn.Module, SupportsMultiModal, SupportsPP):
"""
VibeVoice ASR model with native vLLM multimodal integration.
This model combines VibeVoice acoustic/semantic tokenizers for audio encoding
with a causal language model for text generation.
"""
@classmethod
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
"""Return the placeholder string format for a given modality.
Returns "<|AUDIO|>" which vLLM inserts into the conversation prompt.
This single placeholder is later expanded by `_get_prompt_updates` into:
[speech_start_id] + [speech_pad_id] * N + [speech_end_id] + [newline_id]
where N = ceil(audio_samples / compress_ratio).
"""
if modality.startswith("audio"):
return "<|AUDIO|>"
raise ValueError(f"Unsupported modality: {modality}")
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
self.config = config
self.audio_encoder = VibeVoiceAudioEncoder(config)
# Pass decoder_config to the language model initialization
decoder_config = getattr(config, "decoder_config", config)
self.language_model = init_vllm_registered_model(
vllm_config=vllm_config,
hf_config=decoder_config,
prefix=maybe_prefix(prefix, "language_model"),
architectures=["Qwen2ForCausalLM"],
)
self.make_empty_intermediate_tensors = (
self.language_model.make_empty_intermediate_tensors
)
# Set the language model dtype for audio encoder output conversion
# This should match vLLM's --dtype flag (e.g., bfloat16, float16, float32)
# Audio encoder internal computation stays in fp32 for numerical precision,
# but output is converted to LM dtype for compatibility
lm_dtype = vllm_config.model_config.dtype
if lm_dtype is not None:
self.audio_encoder._lm_dtype = lm_dtype
# Ensure audio encoder uses correct dtype (typically fp32 for precision)
try:
self.audio_encoder._ensure_audio_encoder_dtype()
except Exception:
pass
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None:
return self.language_model.compute_logits(hidden_states)
def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
"""
Extract audio embeddings using VibeVoice's acoustic/semantic tokenizers.
Called by vLLM to get audio embeddings that replace audio placeholder tokens.
Returns:
Tuple of embedding tensors, one per audio input.
"""
# Get raw audio data (stored by our processor)
raw_audio = kwargs.get("raw_audio")
raw_audio_lengths = kwargs.get("raw_audio_lengths")
# Handle no audio input - this happens during memory profiling
if raw_audio is None:
return []
# Handle empty audio list
if isinstance(raw_audio, (list, tuple)) and len(raw_audio) == 0:
return []
# Flatten raw_audio_lengths if it's nested
def flatten_lengths(lengths):
"""Flatten nested lists/tensors of lengths to a single list."""
if lengths is None:
return []
result = []
if isinstance(lengths, torch.Tensor):
lengths = lengths.tolist()
if isinstance(lengths, (list, tuple)):
for item in lengths:
if isinstance(item, (list, tuple)):
result.extend(flatten_lengths(item))
elif isinstance(item, torch.Tensor):
if item.dim() == 0:
result.append(item.item())
else:
result.extend(item.tolist())
else:
result.append(item)
else:
result.append(lengths)
return result
raw_audio_lengths = flatten_lengths(raw_audio_lengths)
# Streaming controls. Enabled by default; can be overridden per-call.
use_streaming_flag = bool(
kwargs.get(
"use_streaming",
getattr(self.audio_encoder, "enable_streaming", True),
)
)
streaming_segment_duration = kwargs.get(
"streaming_segment_duration",
getattr(self.audio_encoder, "streaming_segment_duration", 60.0),
)
# Process each audio through the VibeVoice encoder
embeddings = []
# Get model device for tensor placement.
# dtype is NOT set here — audio_encoder.forward() handles it internally:
# input: converted to fp32 (self._audio_encoder_dtype)
# output: converted to bfloat16 (self._lm_dtype)
try:
device = next(self.audio_encoder.parameters()).device
except StopIteration:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Handle both stacked tensor and list of tensors
# vLLM batches as: [batch_size, 1, seq_len] or [batch_size, seq_len]
if isinstance(raw_audio, torch.Tensor):
if raw_audio.dim() == 3:
# Shape: [batch_size, 1, seq_len] - squeeze the middle dimension
num_audios = raw_audio.shape[0]
audio_list = [raw_audio[i].squeeze(0) for i in range(num_audios)]
elif raw_audio.dim() == 2:
# Shape: [batch_size, seq_len]
num_audios = raw_audio.shape[0]
audio_list = [raw_audio[i] for i in range(num_audios)]
else:
# Single 1D tensor
audio_list = [raw_audio]
elif isinstance(raw_audio, (list, tuple)):
audio_list = list(raw_audio)
else:
# Single tensor
audio_list = [raw_audio]
for i, audio_tensor in enumerate(audio_list):
try:
if isinstance(audio_tensor, list):
audio_tensor = torch.stack(audio_tensor)
# Ensure tensor
if not isinstance(audio_tensor, torch.Tensor):
audio_tensor = torch.tensor(audio_tensor)
# Only place on correct device; audio_encoder.forward() handles dtype
audio_tensor = audio_tensor.to(device=device)
# Get actual length if available, otherwise use full length
if raw_audio_lengths and i < len(raw_audio_lengths):
actual_len = int(raw_audio_lengths[i])
if actual_len > 0 and actual_len <= audio_tensor.shape[-1]:
# Truncate from the last dimension (sequence length)
audio_tensor = audio_tensor[..., :actual_len]
# Skip if audio is too short (< 1 frame)
if audio_tensor.numel() < 160: # Minimum ~1ms at 24kHz
continue
# Encode audio through VibeVoice encoder
audio_embeds = self.audio_encoder(
audio_tensor,
use_streaming=use_streaming_flag,
segment_duration_s=streaming_segment_duration,
)
# audio_embeds shape: [1, seq_len, hidden_size]
# We need to return it as a single embedding tensor per audio
final_embed = audio_embeds.squeeze(0)
embeddings.append(final_embed)
except Exception as e:
# Log error but don't crash - this helps debug profiling issues
print(f"[VibeVoice] Error encoding audio {i}: {e}")
import traceback
traceback.print_exc()
# Return empty embedding to avoid crash
continue
return tuple(embeddings)
def get_input_embeddings(self) -> torch.nn.Module:
"""Return the text embedding layer (embed_tokens).
vLLM uses this to get the embedding module for converting token IDs
to embeddings during decode phase.
Returns:
The embed_tokens module from the language model
"""
# Get embed_tokens from the language model
if hasattr(self.language_model, 'model') and hasattr(self.language_model.model, 'embed_tokens'):
return self.language_model.model.embed_tokens
elif hasattr(self.language_model, 'embed_tokens'):
return self.language_model.embed_tokens
else:
# Try to get from inner model
inner = self.language_model
if hasattr(inner, 'language_model'):
inner = inner.language_model
if hasattr(inner, 'model') and hasattr(inner.model, 'embed_tokens'):
return inner.model.embed_tokens
raise AttributeError("Cannot find embed_tokens layer")
def embed_input_ids(
self,
input_ids: torch.Tensor,
multimodal_embeddings: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
is_multimodal: Optional[torch.Tensor] = None,
**kwargs, # Accept any additional kwargs for compatibility
) -> torch.Tensor:
"""Apply token embeddings to input_ids and merge with multimodal embeddings.
This is the preferred method in vLLM V1 for converting token IDs
to embeddings and merging multimodal (audio) embeddings.
Args:
input_ids: Tensor of token IDs to embed
multimodal_embeddings: Pre-computed multimodal embeddings (audio).
Can be a Tensor or a List of Tensors (vLLM standard).
is_multimodal: Boolean mask indicating which positions are multimodal
**kwargs: Additional arguments for compatibility
Returns:
Tensor of embeddings with multimodal content merged in
"""
from vllm.model_executor.models.utils import _merge_multimodal_embeddings
# Get text embeddings
embed_tokens = self.get_input_embeddings()
inputs_embeds = embed_tokens(input_ids)
# Merge multimodal embeddings if provided
if multimodal_embeddings is not None and is_multimodal is not None:
# Use vLLM's standard merge function which handles List[Tensor] correctly
inputs_embeds = _merge_multimodal_embeddings(
inputs_embeds,
multimodal_embeddings,
is_multimodal,
)
return inputs_embeds
def get_language_model(self) -> torch.nn.Module:
"""Return the language model backbone."""
return self.language_model
def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]) -> set[str]:
"""Load model weights from checkpoint.
The checkpoint has weights named like:
- lm_head.weight -> language_model.lm_head.weight
- model.language_model.layers.X... -> language_model.model.layers.X...
- model.acoustic_tokenizer... -> audio_encoder.acoustic_tokenizer...
- model.semantic_tokenizer... -> audio_encoder.semantic_tokenizer...
- model.acoustic_connector... -> audio_encoder.acoustic_connector...
- model.semantic_connector... -> audio_encoder.semantic_connector...
Let vLLM handle all dtype conversions according to --dtype flag.
"""
# Map weight prefixes for VibeVoice
# The checkpoint uses "model." prefix, we need to remap it
mapper = WeightsMapper(
orig_to_new_prefix={
# Audio encoder components: model.X -> audio_encoder.X
"model.acoustic_tokenizer.": "audio_encoder.acoustic_tokenizer.",
"model.semantic_tokenizer.": "audio_encoder.semantic_tokenizer.",
"model.acoustic_connector.": "audio_encoder.acoustic_connector.",
"model.semantic_connector.": "audio_encoder.semantic_connector.",
# Language model: model.language_model.X -> language_model.model.X
"model.language_model.": "language_model.model.",
# LM head: lm_head.X -> language_model.lm_head.X
"lm_head.": "language_model.lm_head.",
}
)
loader = AutoWeightsLoader(self)
return loader.load_weights(weights, mapper=mapper)
def forward(
self,
input_ids: Optional[torch.Tensor],
positions: torch.Tensor,
intermediate_tensors: Optional[IntermediateTensors] = None,
inputs_embeds: Optional[torch.Tensor] = None,
**kwargs: object,
) -> Union[torch.Tensor, IntermediateTensors]:
"""
Forward pass for VibeVoice ASR model.
Handles embedding computation and language model forward pass.
Uses inputs_embeds if provided (from vLLM multimodal merge),
otherwise computes embeddings from input_ids.
Args:
input_ids: Token IDs. May be None when inputs_embeds is provided.
positions: Position indices for the input tokens.
intermediate_tensors: Intermediate tensors for pipeline parallelism.
inputs_embeds: Pre-computed embeddings (from multimodal merge or decode).
"""
# PRIORITY: Use inputs_embeds if provided (from vLLM multimodal merge or decode)
# Only compute from input_ids if inputs_embeds is not available
if inputs_embeds is None and input_ids is not None:
# Compute embeddings from input_ids
inputs_embeds = self.get_input_embeddings()(input_ids)
# If we have intermediate tensors (pipeline parallelism), don't use inputs_embeds
if intermediate_tensors is not None:
inputs_embeds = None
# Get the inner model - handle both wrapped and direct language models
language_model = self.language_model
if hasattr(language_model, "language_model"):
language_model = language_model.language_model
# Call the language model's model (Qwen2Model)
# vLLM V1 passes kv_caches and attn_metadata via context, not arguments
# IMPORTANT: Pass input_ids=None when using inputs_embeds to avoid double embedding
hidden_states = language_model.model(
input_ids=None, # Always None when we have inputs_embeds
positions=positions,
intermediate_tensors=intermediate_tensors,
inputs_embeds=inputs_embeds
)
return hidden_states
# Alias for training checkpoint compatibility
VibeVoiceForASRTraining = VibeVoiceForCausalLM
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/model.py",
"license": "MIT License",
"lines": 1057,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vllm_plugin/tests/test_api.py | #!/usr/bin/env python3
"""
Test VibeVoice vLLM API with Streaming and Optional Hotwords Support.
This script tests ASR transcription via the vLLM OpenAI-compatible API.
By default, it runs standard transcription without hotwords.
Optionally, you can provide hotwords (context_info) to improve recognition
of domain-specific content like proper nouns, technical terms, and speaker names.
Hotwords are embedded in the prompt as "with extra info: {hotwords}".
Usage:
python test_api_with_hotwords.py [audio_path] [--url URL] [--hotwords "word1,word2"]
Examples:
# Standard transcription (no hotwords)
python3 test_api.py audio.wav
# With hotwords for better recognition of specific terms
python3 test_api.py audio.wav --hotwords "Microsoft,Azure,VibeVoice"
"""
import requests
import json
import base64
import time
import sys
import os
import subprocess
import argparse
def _guess_mime_type(path: str) -> str:
"""Guess MIME type from file extension."""
ext = os.path.splitext(path)[1].lower()
mime_map = {
".wav": "audio/wav",
".mp3": "audio/mpeg",
".m4a": "audio/mp4",
".mp4": "video/mp4",
".flac": "audio/flac",
".ogg": "audio/ogg",
".opus": "audio/ogg",
}
return mime_map.get(ext, "application/octet-stream")
def _get_duration_seconds_ffprobe(path: str) -> float:
"""Get audio duration using ffprobe."""
cmd = [
"ffprobe", "-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
path,
]
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8").strip()
return float(out)
def _is_video_file(path: str) -> bool:
"""Check if the file is a video file that needs audio extraction."""
ext = os.path.splitext(path)[1].lower()
return ext in (".mp4", ".m4v", ".mov", ".webm", ".avi", ".mkv")
def _extract_audio_from_video(video_path: str) -> str:
"""
Extract audio from video file (mp4/mov/webm) to a temporary mp3 file.
Returns the path to the extracted audio file.
"""
import tempfile
# Create temp file with .mp3 extension
fd, audio_path = tempfile.mkstemp(suffix=".mp3")
os.close(fd)
cmd = [
"ffmpeg", "-y", "-i", video_path,
"-vn", # No video
"-acodec", "libmp3lame",
"-q:a", "2", # High quality
audio_path
]
subprocess.run(cmd, check=True, capture_output=True)
return audio_path
def test_transcription_with_hotwords(
audio_path: str,
context_info: str = None,
base_url: str = "http://localhost:8000",
):
"""
Test ASR transcription with customized hotwords.
Hotwords are embedded in the prompt text as "with extra info: {hotwords}".
This helps the model recognize domain-specific terms more accurately.
Args:
audio_path: Path to the audio file
context_info: Hotwords string (e.g., "Microsoft,Azure,VibeVoice")
base_url: vLLM server URL
"""
print(f"=" * 70)
print(f"Testing Customized Hotwords Support")
print(f"=" * 70)
print(f"Input file: {audio_path}")
print(f"Hotwords: {context_info or '(none)'}")
print()
# Handle video files: extract audio first
temp_audio_path = None
actual_audio_path = audio_path
if _is_video_file(audio_path):
print(f"🎬 Detected video file, extracting audio...")
temp_audio_path = _extract_audio_from_video(audio_path)
actual_audio_path = temp_audio_path
print(f"✅ Audio extracted to: {temp_audio_path}")
# Load audio
try:
duration = _get_duration_seconds_ffprobe(actual_audio_path)
print(f"Audio duration: {duration:.2f} seconds")
with open(actual_audio_path, "rb") as f:
audio_bytes = f.read()
audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
print(f"Audio size: {len(audio_bytes)} bytes")
except Exception as e:
print(f"Error preparing audio: {e}")
# Cleanup temp file if created
if temp_audio_path and os.path.exists(temp_audio_path):
os.remove(temp_audio_path)
return
# Build the request
url = f"{base_url}/v1/chat/completions"
show_keys = ["Start time", "End time", "Speaker ID", "Content"]
# Build prompt with optional hotwords
# Hotwords are embedded as "with extra info: {hotwords}" in the prompt
if context_info and context_info.strip():
prompt_text = (
f"This is a {duration:.2f} seconds audio, with extra info: {context_info.strip()}\n\n"
f"Please transcribe it with these keys: " + ", ".join(show_keys)
)
print(f"\n📝 Hotwords embedded in prompt: '{context_info}'")
else:
prompt_text = (
f"This is a {duration:.2f} seconds audio, please transcribe it with these keys: "
+ ", ".join(show_keys)
)
print(f"\n📝 No hotwords provided")
mime = _guess_mime_type(actual_audio_path)
data_url = f"data:{mime};base64,{audio_b64}"
payload = {
"model": "vibevoice",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that transcribes audio input into text output in JSON format."
},
{
"role": "user",
"content": [
{"type": "audio_url", "audio_url": {"url": data_url}},
{"type": "text", "text": prompt_text}
]
}
],
"max_tokens": 32768,
"temperature": 0.0,
"stream": True,
"top_p": 1.0,
}
print(f"\n{'=' * 70}")
print(f"Sending request to {url}")
print(f"{'=' * 70}")
t0 = time.time()
try:
response = requests.post(url, json=payload, stream=True, timeout=12000)
if response.status_code == 200:
print("\n✅ Response received. Streaming content:\n")
print("-" * 50)
printed = ""
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith("data: "):
json_str = decoded_line[6:]
if json_str.strip() == "[DONE]":
print("\n" + "-" * 50)
print("✅ [Finished]")
break
try:
data = json.loads(json_str)
delta = data['choices'][0]['delta']
content = delta.get('content', '')
if content:
if content.startswith(printed):
to_print = content[len(printed):]
else:
to_print = content
if to_print:
print(to_print, end='', flush=True)
printed += to_print
except json.JSONDecodeError:
pass
else:
print(f"❌ Error: {response.status_code}")
print(response.text)
except requests.exceptions.Timeout:
print("❌ Request timed out!")
except Exception as e:
print(f"❌ Error: {e}")
elapsed = time.time() - t0
print(f"\n{'=' * 70}")
print(f"⏱️ Total time elapsed: {elapsed:.2f}s")
print(f"📊 RTF (Real-Time Factor): {elapsed / duration:.2f}x")
print(f"{'=' * 70}")
# Cleanup temp audio file if created
if temp_audio_path and os.path.exists(temp_audio_path):
os.remove(temp_audio_path)
print(f"🗑️ Cleaned up temp file: {temp_audio_path}")
def main():
parser = argparse.ArgumentParser(
description="Test VibeVoice vLLM API with Customized Hotwords"
)
parser.add_argument(
"audio_path",
help="Path to audio file (wav, mp3, flac, etc.) or video file"
)
parser.add_argument(
"--url",
default="http://localhost:8000",
help="vLLM server URL (default: http://localhost:8000)"
)
parser.add_argument(
"--hotwords",
type=str,
default=None,
help="Hotwords to improve recognition (e.g., 'Microsoft,Azure,VibeVoice')"
)
args = parser.parse_args()
# Run test
test_transcription_with_hotwords(
audio_path=args.audio_path,
context_info=args.hotwords,
base_url=args.url,
)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/tests/test_api.py",
"license": "MIT License",
"lines": 227,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/VibeVoice:vllm_plugin/tools/generate_tokenizer_files.py | #!/usr/bin/env python3
"""
Standalone tool to generate VibeVoice tokenizer files from Qwen2 base.
Downloads base tokenizer from Qwen2 and patches it with VibeVoice-specific
audio tokens and chat template modifications.
Usage:
python generate_tokenizer_files.py --output /path/to/output [--compare /path/to/reference]
"""
import argparse
import json
import os
import shutil
import tempfile
from typing import Optional, Dict, Any
# Qwen2.5 extended tokens (151646-151664)
# These are NOT in base Qwen2-7B but ARE in Qwen2.5 and Qwen2-VL
# VibeVoice uses some of these for speech: object_ref_start/end, box_start
QWEN25_EXTENDED_TOKENS = {
"<|object_ref_start|>": 151646, # Used as speech_start_id
"<|object_ref_end|>": 151647, # Used as speech_end_id
"<|box_start|>": 151648, # Used as speech_pad_id
"<|box_end|>": 151649,
"<|quad_start|>": 151650,
"<|quad_end|>": 151651,
"<|vision_start|>": 151652,
"<|vision_end|>": 151653,
"<|vision_pad|>": 151654,
"<|image_pad|>": 151655,
"<|video_pad|>": 151656,
"<tool_call>": 151657,
"</tool_call>": 151658,
"<|fim_prefix|>": 151659,
"<|fim_middle|>": 151660,
"<|fim_suffix|>": 151661,
"<|fim_pad|>": 151662,
"<|repo_name|>": 151663,
"<|file_sep|>": 151664,
}
# VibeVoice-specific audio tokens (IDs follow Qwen2.5's last token 151664)
VIBEVOICE_AUDIO_TOKENS = {
"<|AUDIO|>": 151665,
"<|audio_bos|>": 151666,
"<|audio_eos|>": 151667,
}
# All extended tokens (Qwen2.5 + VibeVoice)
ALL_EXTENDED_TOKENS = {**QWEN25_EXTENDED_TOKENS, **VIBEVOICE_AUDIO_TOKENS}
# Chat template with audio support
# Key modification: handles part['type'] == 'audio' or 'audio_url' -> '<|AUDIO|>'
VIBEVOICE_CHAT_TEMPLATE = """{%- if tools %}
{{- '<|im_start|>system\\n' }}
{%- if messages[0]['role'] == 'system' %}
{%- if messages[0]['content'] is string %}
{{- messages[0]['content'] }}
{%- else %}
{%- for part in messages[0]['content'] %}
{%- if part['type'] == 'text' %}
{{- part['text'] }}
{%- elif part['type'] == 'audio' or part['type'] == 'audio_url' %}
{{- '<|AUDIO|>' }}
{%- endif %}
{%- endfor %}
{%- endif %}
{%- else %}
{{- 'You are a helpful assistant.' }}
{%- endif %}
{{- "\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>" }}
{%- for tool in tools %}
{{- "\\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\"name\\": <function-name>, \\"arguments\\": <args-json-object>}\\n</tool_call><|im_end|>\\n" }}
{%- else %}
{%- if messages[0]['role'] == 'system' %}
{{- '<|im_start|>system\\n' }}
{%- if messages[0]['content'] is string %}
{{- messages[0]['content'] }}
{%- else %}
{%- for part in messages[0]['content'] %}
{%- if part['type'] == 'text' %}
{{- part['text'] }}
{%- elif part['type'] == 'audio' or part['type'] == 'audio_url' %}
{{- '<|AUDIO|>' }}
{%- endif %}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\\n' }}
{%- else %}
{{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}
{%- endif %}
{%- endif %}
{%- for message in messages %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
{{- '<|im_start|>' + message.role + '\\n' }}
{%- if message['content'] is string %}
{{- message['content'] }}
{%- else %}
{%- for part in message['content'] %}
{%- if part['type'] == 'text' %}
{{- part['text'] }}
{%- elif part['type'] == 'audio' or part['type'] == 'audio_url' %}
{{- '<|AUDIO|>' }}
{%- endif %}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\\n' }}
{%- elif message.role == "assistant" %}
{{- '<|im_start|>' + message.role }}
{%- if message.content %}
{{- '\\n' + message.content }}
{%- endif %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '\\n<tool_call>\\n{"name": "' }}
{{- tool_call.name }}
{{- '", "arguments": ' }}
{{- tool_call.arguments | tojson }}
{{- '}\\n</tool_call>' }}
{%- endfor %}
{{- '<|im_end|>\\n' }}
{%- elif message.role == "tool" %}
{%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\\n<tool_response>\\n' }}
{{- message.content }}
{{- '\\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\\n' }}
{%- endif %}"""
# Default to Qwen2.5-7B which has all the extended tokens (151646-151664)
DEFAULT_QWEN_MODEL = "Qwen/Qwen2.5-7B"
def download_qwen_tokenizer_files(output_dir: str, qwen_model: str = DEFAULT_QWEN_MODEL) -> None:
"""Download base tokenizer files from Qwen2.5 (which includes extended tokens)."""
try:
from huggingface_hub import hf_hub_download
except ImportError:
raise ImportError("Please install huggingface_hub: pip install huggingface_hub")
files_to_download = [
"vocab.json",
"merges.txt",
"tokenizer.json",
"tokenizer_config.json",
]
os.makedirs(output_dir, exist_ok=True)
for filename in files_to_download:
print(f"Downloading {filename} from {qwen_model}...")
hf_hub_download(
repo_id=qwen_model,
filename=filename,
local_dir=output_dir,
local_dir_use_symlinks=False,
)
def patch_tokenizer_config(output_dir: str) -> None:
"""
Patch tokenizer_config.json with VibeVoice audio tokens and chat template.
"""
config_path = os.path.join(output_dir, "tokenizer_config.json")
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
# 1. Add ALL extended tokens to added_tokens_decoder (Qwen2.5 + VibeVoice audio)
if "added_tokens_decoder" not in config:
config["added_tokens_decoder"] = {}
for token, token_id in ALL_EXTENDED_TOKENS.items():
if str(token_id) not in config["added_tokens_decoder"]:
# Determine if token should be marked as "special"
# tool_call tokens are NOT special in Qwen2.5
is_special = token not in ("<tool_call>", "</tool_call>", "<|fim_prefix|>",
"<|fim_middle|>", "<|fim_suffix|>", "<|fim_pad|>",
"<|repo_name|>", "<|file_sep|>")
config["added_tokens_decoder"][str(token_id)] = {
"content": token,
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
"special": is_special,
}
# 2. Add audio tokens to additional_special_tokens
if "additional_special_tokens" not in config:
config["additional_special_tokens"] = []
for token in VIBEVOICE_AUDIO_TOKENS.keys():
if token not in config["additional_special_tokens"]:
config["additional_special_tokens"].append(token)
# 3. Modify chat_template to support audio
# Instead of replacing entirely, we patch the existing template to handle audio
chat_template = config.get("chat_template", "")
if chat_template and "<|AUDIO|>" not in chat_template:
# Insert audio handling into the template
# Find patterns like: {%- if part['type'] == 'text' %}
# Add after: {%- elif part['type'] == 'audio' or part['type'] == 'audio_url' %}\n {{- '<|AUDIO|>' }}
audio_handler = """{%- elif part['type'] == 'audio' or part['type'] == 'audio_url' %}
{{- '<|AUDIO|>' }}"""
# Pattern to find: after handling 'text' type, before endif
import re
# Look for the pattern where we handle text type and add audio handling
pattern = r"(\{\%- if part\['type'\] == 'text' \%\}\s*\n\s*\{\{- part\['text'\] \}\})"
replacement = r"\1\n " + audio_handler.replace("\n", r"\n")
modified_template = re.sub(pattern, replacement, chat_template)
if modified_template != chat_template:
config["chat_template"] = modified_template
print(" - Added audio support to existing chat_template")
else:
# Fallback: use our predefined template
print(" - Warning: Could not patch existing template, using predefined template")
config["chat_template"] = VIBEVOICE_CHAT_TEMPLATE
# 4. Update model_max_length for long audio support
config["model_max_length"] = 131072
# 5. Add add_bos_token if not present
if "add_bos_token" not in config:
config["add_bos_token"] = False
# Write back
with open(config_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
print(f"Patched {config_path}")
def patch_tokenizer_json(output_dir: str) -> None:
"""
Patch tokenizer.json with VibeVoice audio tokens.
"""
tokenizer_path = os.path.join(output_dir, "tokenizer.json")
with open(tokenizer_path, "r", encoding="utf-8") as f:
tokenizer = json.load(f)
# Find existing token IDs to avoid duplicates
existing_ids = set()
if "added_tokens" in tokenizer:
for token_entry in tokenizer["added_tokens"]:
existing_ids.add(token_entry.get("id"))
# Add ALL extended tokens (Qwen2.5 + VibeVoice audio)
for token, token_id in ALL_EXTENDED_TOKENS.items():
if token_id not in existing_ids:
# Determine if token should be marked as "special"
is_special = token not in ("<tool_call>", "</tool_call>", "<|fim_prefix|>",
"<|fim_middle|>", "<|fim_suffix|>", "<|fim_pad|>",
"<|repo_name|>", "<|file_sep|>")
tokenizer["added_tokens"].append({
"id": token_id,
"content": token,
"single_word": False,
"lstrip": False,
"rstrip": False,
"normalized": False,
"special": is_special,
})
# Write back
with open(tokenizer_path, "w", encoding="utf-8") as f:
json.dump(tokenizer, f, indent=2, ensure_ascii=False)
print(f"Patched {tokenizer_path}")
def generate_added_tokens_json(output_dir: str) -> None:
"""
Generate added_tokens.json from tokenizer_config.json.
"""
config_path = os.path.join(output_dir, "tokenizer_config.json")
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
added_tokens = {}
for token_id, token_info in config.get("added_tokens_decoder", {}).items():
content = token_info.get("content")
if content:
added_tokens[content] = int(token_id)
output_path = os.path.join(output_dir, "added_tokens.json")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(added_tokens, f, indent=2, ensure_ascii=False)
print(f"Generated {output_path}")
def generate_special_tokens_map_json(output_dir: str) -> None:
"""
Generate special_tokens_map.json with VibeVoice special tokens.
"""
# Build the special tokens map
special_tokens_map = {
"additional_special_tokens": [],
"eos_token": "<|endoftext|>",
"pad_token": "<|endoftext|>",
"unk_token": "<|endoftext|>",
}
# Add audio tokens as additional_special_tokens
for token in VIBEVOICE_AUDIO_TOKENS.keys():
special_tokens_map["additional_special_tokens"].append({
"content": token,
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
})
# Add some commonly used special tokens
common_special = ["<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>"]
for token in common_special:
special_tokens_map["additional_special_tokens"].append({
"content": token,
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
})
output_path = os.path.join(output_dir, "special_tokens_map.json")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(special_tokens_map, f, indent=2, ensure_ascii=False)
print(f"Generated {output_path}")
def generate_vibevoice_tokenizer_files(output_dir: str, qwen_model: str = DEFAULT_QWEN_MODEL) -> None:
"""
Generate all 6 VibeVoice tokenizer files.
Files generated:
1. vocab.json - from Qwen2.5 (unchanged)
2. merges.txt - from Qwen2.5 (unchanged)
3. tokenizer.json - from Qwen2.5 + audio tokens
4. tokenizer_config.json - from Qwen2.5 + audio tokens + chat_template
5. added_tokens.json - generated from tokenizer_config.json
6. special_tokens_map.json - generated with VibeVoice tokens
"""
print(f"=== Generating VibeVoice tokenizer files to {output_dir} ===\n")
# Step 1: Download base files from Qwen2
download_qwen_tokenizer_files(output_dir, qwen_model)
# Step 2: Patch tokenizer_config.json
patch_tokenizer_config(output_dir)
# Step 3: Patch tokenizer.json
patch_tokenizer_json(output_dir)
# Step 4: Generate added_tokens.json
generate_added_tokens_json(output_dir)
# Step 5: Generate special_tokens_map.json
generate_special_tokens_map_json(output_dir)
print(f"\n✅ All 6 tokenizer files generated in {output_dir}")
def compare_json_files(file1: str, file2: str, name: str) -> Dict[str, Any]:
"""Compare two JSON files and return differences."""
result = {
"name": name,
"identical": False,
"differences": [],
}
if not os.path.exists(file1):
result["differences"].append(f"File 1 not found: {file1}")
return result
if not os.path.exists(file2):
result["differences"].append(f"File 2 not found: {file2}")
return result
with open(file1, "r", encoding="utf-8") as f:
data1 = json.load(f)
with open(file2, "r", encoding="utf-8") as f:
data2 = json.load(f)
if data1 == data2:
result["identical"] = True
return result
# Find specific differences
def find_diff(d1, d2, path=""):
diffs = []
if isinstance(d1, dict) and isinstance(d2, dict):
all_keys = set(d1.keys()) | set(d2.keys())
for k in all_keys:
new_path = f"{path}.{k}" if path else k
if k not in d1:
diffs.append(f"Missing in generated: {new_path}")
elif k not in d2:
diffs.append(f"Extra in generated: {new_path}")
else:
diffs.extend(find_diff(d1[k], d2[k], new_path))
elif isinstance(d1, list) and isinstance(d2, list):
if len(d1) != len(d2):
diffs.append(f"{path}: list length differs ({len(d1)} vs {len(d2)})")
# For lists, just check if they're equal (detailed diff is complex)
if d1 != d2:
diffs.append(f"{path}: list content differs")
elif d1 != d2:
# Truncate long values for readability
v1 = str(d1)[:100] + "..." if len(str(d1)) > 100 else str(d1)
v2 = str(d2)[:100] + "..." if len(str(d2)) > 100 else str(d2)
diffs.append(f"{path}: '{v1}' vs '{v2}'")
return diffs
result["differences"] = find_diff(data1, data2)
return result
def compare_text_files(file1: str, file2: str, name: str) -> Dict[str, Any]:
"""Compare two text files."""
result = {
"name": name,
"identical": False,
"differences": [],
}
if not os.path.exists(file1):
result["differences"].append(f"File 1 not found: {file1}")
return result
if not os.path.exists(file2):
result["differences"].append(f"File 2 not found: {file2}")
return result
with open(file1, "r", encoding="utf-8") as f:
content1 = f.read()
with open(file2, "r", encoding="utf-8") as f:
content2 = f.read()
if content1 == content2:
result["identical"] = True
else:
lines1 = content1.splitlines()
lines2 = content2.splitlines()
result["differences"].append(f"Line count: {len(lines1)} vs {len(lines2)}")
# Find first difference
for i, (l1, l2) in enumerate(zip(lines1, lines2)):
if l1 != l2:
result["differences"].append(f"First diff at line {i+1}")
break
return result
def compare_with_reference(generated_dir: str, reference_dir: str) -> None:
"""Compare generated files with reference files."""
print(f"\n=== Comparing generated files with reference ===")
print(f"Generated: {generated_dir}")
print(f"Reference: {reference_dir}\n")
files_to_compare = [
("vocab.json", "json"),
("merges.txt", "text"),
("tokenizer.json", "json"),
("tokenizer_config.json", "json"),
("added_tokens.json", "json"),
("special_tokens_map.json", "json"),
]
all_identical = True
for filename, file_type in files_to_compare:
gen_file = os.path.join(generated_dir, filename)
ref_file = os.path.join(reference_dir, filename)
if file_type == "json":
result = compare_json_files(gen_file, ref_file, filename)
else:
result = compare_text_files(gen_file, ref_file, filename)
if result["identical"]:
print(f"✅ {filename}: IDENTICAL")
else:
print(f"❌ {filename}: DIFFERENT")
for diff in result["differences"][:5]: # Show first 5 differences
print(f" - {diff}")
if len(result["differences"]) > 5:
print(f" ... and {len(result['differences']) - 5} more differences")
all_identical = False
print()
if all_identical:
print("🎉 All files are identical!")
else:
print("⚠️ Some files have differences. See details above.")
def main():
parser = argparse.ArgumentParser(
description="Generate VibeVoice tokenizer files from Qwen2 base"
)
parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output directory for generated files (default: temp directory)"
)
parser.add_argument(
"--compare", "-c",
type=str,
default=None,
help="Reference directory to compare generated files against"
)
parser.add_argument(
"--qwen-model",
type=str,
default=DEFAULT_QWEN_MODEL,
help=f"Qwen model to download base tokenizer from (default: {DEFAULT_QWEN_MODEL})"
)
args = parser.parse_args()
# Determine output directory
if args.output:
output_dir = args.output
cleanup = False
else:
output_dir = tempfile.mkdtemp(prefix="vibevoice_tokenizer_")
cleanup = not args.compare # Only cleanup if not comparing
try:
# Generate files
generate_vibevoice_tokenizer_files(output_dir, args.qwen_model)
# Compare if requested
if args.compare:
compare_with_reference(output_dir, args.compare)
if not args.output:
print(f"\nGenerated files are in: {output_dir}")
finally:
if cleanup and not args.output:
print(f"\nCleaning up temporary directory: {output_dir}")
shutil.rmtree(output_dir, ignore_errors=True)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vllm_plugin/tools/generate_tokenizer_files.py",
"license": "MIT License",
"lines": 481,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:demo/vibevoice_asr_gradio_demo.py | #!/usr/bin/env python
"""
VibeVoice ASR Gradio Demo
"""
import os
import sys
import torch
import numpy as np
import soundfile as sf
from pathlib import Path
import argparse
import time
import json
import gradio as gr
from typing import List, Dict, Tuple, Optional, Generator
import tempfile
import base64
import io
import traceback
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
# Import TextIteratorStreamer for streaming generation
from transformers import TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList
try:
from liger_kernel.transformers import apply_liger_kernel_to_qwen2
# Only apply RoPE, RMSNorm, SwiGLU patches (these affect the underlying Qwen2 layers)
apply_liger_kernel_to_qwen2(
rope=True,
rms_norm=True,
swiglu=True,
cross_entropy=False,
)
print("✅ Liger Kernel applied to Qwen2 components (RoPE, RMSNorm, SwiGLU)")
except Exception as e:
print(f"⚠️ Failed to apply Liger Kernel: {e}, you can install it with: pip install liger-kernel")
# Try to import pydub for MP3 conversion
try:
from pydub import AudioSegment
HAS_PYDUB = True
except ImportError:
HAS_PYDUB = False
print("⚠️ Warning: pydub not available, falling back to WAV format")
from vibevoice.modular.modeling_vibevoice_asr import VibeVoiceASRForConditionalGeneration
from vibevoice.processor.vibevoice_asr_processor import VibeVoiceASRProcessor
from vibevoice.processor.audio_utils import load_audio_use_ffmpeg, COMMON_AUDIO_EXTS
class VibeVoiceASRInference:
"""Simple inference wrapper for VibeVoice ASR model."""
def __init__(self, model_path: str, device: str = "cuda", dtype: torch.dtype = torch.bfloat16, attn_implementation: str = "flash_attention_2"):
"""
Initialize the ASR inference pipeline.
Args:
model_path: Path to the pretrained model (HuggingFace format directory or model name)
device: Device to run inference on
dtype: Data type for model weights
attn_implementation: Attention implementation to use ('flash_attention_2', 'sdpa', 'eager')
"""
print(f"Loading VibeVoice ASR model from {model_path}")
# Load processor
self.processor = VibeVoiceASRProcessor.from_pretrained(model_path)
# Load model
print(f"Using attention implementation: {attn_implementation}")
self.model = VibeVoiceASRForConditionalGeneration.from_pretrained(
model_path,
dtype=dtype,
device_map=device if device == "auto" else None,
attn_implementation=attn_implementation,
trust_remote_code=True
)
if device != "auto":
self.model = self.model.to(device)
self.device = device if device != "auto" else next(self.model.parameters()).device
self.model.eval()
# Print model info
total_params = sum(p.numel() for p in self.model.parameters())
print(f"✅ Model loaded successfully on {self.device}")
print(f"📊 Total parameters: {total_params:,} ({total_params/1e9:.2f}B)")
def transcribe(
self,
audio_path: str = None,
audio_array: np.ndarray = None,
sample_rate: int = None,
max_new_tokens: int = 512,
temperature: float = 0.0,
top_p: float = 1.0,
do_sample: bool = False,
num_beams: int = 1,
repetition_penalty: float = 1.0,
context_info: str = None,
streamer: Optional[TextIteratorStreamer] = None,
) -> dict:
"""
Transcribe audio to text.
Args:
audio_path: Path to audio file
audio_array: Audio array (if not loading from file)
sample_rate: Sample rate of audio array
max_new_tokens: Maximum tokens to generate
temperature: Temperature for sampling (0 for greedy)
top_p: Top-p for nucleus sampling (1.0 for no filtering)
do_sample: Whether to use sampling
num_beams: Number of beams for beam search (1 for greedy)
repetition_penalty: Repetition penalty (1.0 for no penalty)
context_info: Optional context information (e.g., hotwords, speaker names, topics) to help transcription
streamer: Optional TextIteratorStreamer for streaming output
Returns:
Dictionary with transcription results
"""
# Process audio
inputs = self.processor(
audio=audio_path,
sampling_rate=sample_rate,
return_tensors="pt",
add_generation_prompt=True,
context_info=context_info
)
# Move to device
inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
for k, v in inputs.items()}
# Generate
generation_config = {
"max_new_tokens": max_new_tokens,
"temperature": temperature if temperature > 0 else None,
"top_p": top_p if do_sample else None,
"do_sample": do_sample,
"num_beams": num_beams,
"repetition_penalty": repetition_penalty,
"pad_token_id": self.processor.pad_id,
"eos_token_id": self.processor.tokenizer.eos_token_id,
}
# Add streamer if provided
if streamer is not None:
generation_config["streamer"] = streamer
# Add stopping criteria for stop button support
generation_config["stopping_criteria"] = StoppingCriteriaList([StopOnFlag()])
# Remove None values
generation_config = {k: v for k, v in generation_config.items() if v is not None}
start_time = time.time()
# Calculate input token statistics before generation
input_ids = inputs['input_ids'][0] # Shape: [seq_len]
total_input_tokens = input_ids.shape[0]
# Count padding tokens (tokens equal to pad_id)
pad_id = self.processor.pad_id
padding_mask = (input_ids == pad_id)
num_padding_tokens = padding_mask.sum().item()
# Count speech tokens (tokens between speech_start_id and speech_end_id)
speech_start_id = self.processor.speech_start_id
speech_end_id = self.processor.speech_end_id
# Find speech regions
input_ids_list = input_ids.tolist()
num_speech_tokens = 0
in_speech = False
for token_id in input_ids_list:
if token_id == speech_start_id:
in_speech = True
num_speech_tokens += 1 # Count speech_start token
elif token_id == speech_end_id:
in_speech = False
num_speech_tokens += 1 # Count speech_end token
elif in_speech:
num_speech_tokens += 1
# Text tokens = total - speech - padding
num_text_tokens = total_input_tokens - num_speech_tokens - num_padding_tokens
with torch.no_grad():
output_ids = self.model.generate(
**inputs,
**generation_config
)
generation_time = time.time() - start_time
# Decode output
generated_ids = output_ids[0, inputs['input_ids'].shape[1]:]
generated_text = self.processor.decode(generated_ids, skip_special_tokens=True)
# Parse structured output
try:
transcription_segments = self.processor.post_process_transcription(generated_text)
except Exception as e:
print(f"Warning: Failed to parse structured output: {e}")
transcription_segments = []
return {
"raw_text": generated_text,
"segments": transcription_segments,
"generation_time": generation_time,
"input_tokens": {
"total": total_input_tokens,
"speech": num_speech_tokens,
"text": num_text_tokens,
"padding": num_padding_tokens,
},
}
def clip_and_encode_audio(
audio_data: np.ndarray,
sr: int,
start_time: float,
end_time: float,
segment_idx: int,
use_mp3: bool = True,
target_sr: int = 16000, # Downsample to 16kHz for smaller size
mp3_bitrate: str = "32k" # Use low bitrate for minimal transfer
) -> Tuple[int, Optional[str], Optional[str]]:
"""
Clip audio segment and encode to base64.
Args:
audio_data: Full audio array
sr: Sample rate
start_time: Start time in seconds
end_time: End time in seconds
segment_idx: Segment index for identification
use_mp3: Whether to use MP3 format (smaller size)
target_sr: Target sample rate for downsampling (lower = smaller)
mp3_bitrate: MP3 bitrate (lower = smaller, e.g., "24k", "32k", "48k")
Returns:
Tuple of (segment_idx, base64_string, error_message)
"""
try:
# Convert time to sample indices
start_sample = int(start_time * sr)
end_sample = int(end_time * sr)
# Ensure indices are within bounds
start_sample = max(0, start_sample)
end_sample = min(len(audio_data), end_sample)
if start_sample >= end_sample:
return segment_idx, None, f"Invalid time range: [{start_time:.2f}s - {end_time:.2f}s]"
# Extract segment
segment_data = audio_data[start_sample:end_sample]
# Downsample if needed (reduces data size significantly)
if sr != target_sr and target_sr < sr:
# Simple downsampling using linear interpolation
duration = len(segment_data) / sr
new_length = int(duration * target_sr)
indices = np.linspace(0, len(segment_data) - 1, new_length)
segment_data = np.interp(indices, np.arange(len(segment_data)), segment_data)
sr = target_sr
# Convert float32 audio to int16 for encoding
segment_data_int16 = (segment_data * 32768.0).astype(np.int16)
# Convert to MP3 if pydub is available and use_mp3 is True
if use_mp3 and HAS_PYDUB:
try:
# Write to WAV in memory
wav_buffer = io.BytesIO()
sf.write(wav_buffer, segment_data_int16, sr, format='WAV', subtype='PCM_16')
wav_buffer.seek(0)
# Convert to MP3 with low bitrate
audio_segment = AudioSegment.from_wav(wav_buffer)
# Convert to mono if stereo (halves the size)
if audio_segment.channels > 1:
audio_segment = audio_segment.set_channels(1)
mp3_buffer = io.BytesIO()
audio_segment.export(mp3_buffer, format='mp3', bitrate=mp3_bitrate)
mp3_buffer.seek(0)
# Encode to base64
audio_bytes = mp3_buffer.read()
audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
audio_src = f"data:audio/mp3;base64,{audio_base64}"
return segment_idx, audio_src, None
except Exception as e:
# Fall back to WAV on error
print(f"MP3 conversion failed for segment {segment_idx}, using WAV: {e}")
# Fall back to WAV format (no temp file, use in-memory buffer)
wav_buffer = io.BytesIO()
sf.write(wav_buffer, segment_data_int16, sr, format='WAV', subtype='PCM_16')
wav_buffer.seek(0)
audio_bytes = wav_buffer.read()
audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
audio_src = f"data:audio/wav;base64,{audio_base64}"
return segment_idx, audio_src, None
except Exception as e:
error_msg = f"Error clipping segment {segment_idx}: {str(e)}"
print(error_msg)
return segment_idx, None, error_msg
def extract_audio_segments(audio_path: str, segments: List[Dict]) -> List[Tuple[str, str, Optional[str]]]:
"""
Extract multiple segments from audio file efficiently with parallel processing.
Args:
audio_path: Path to original audio file
segments: List of segment dictionaries with start_time, end_time, etc.
Returns:
List of tuples (segment_label, audio_base64_src, error_msg)
"""
try:
# Read audio file once using ffmpeg for better format support
print(f"📂 Loading audio file: {audio_path}")
audio_data, sr = load_audio_use_ffmpeg(audio_path, resample=False)
print(f"✅ Audio loaded: {len(audio_data)} samples, {sr} Hz")
# Prepare tasks
tasks = []
use_mp3 = HAS_PYDUB # Use MP3 if available
for i, seg in enumerate(segments):
start_time = seg.get('start_time')
end_time = seg.get('end_time')
# Skip if times are not available or invalid
if (not isinstance(start_time, (int, float)) or
not isinstance(end_time, (int, float)) or
start_time >= end_time):
tasks.append((i, None, None, None, None, None)) # Will be filtered later
continue
tasks.append((audio_data, sr, start_time, end_time, i, use_mp3))
# Process in parallel using ThreadPoolExecutor
results = []
total_segments = len(tasks)
completed_count = 0
# Use CPU count for max workers
max_workers = os.cpu_count() or 4
print(f"🚀 Starting parallel processing with {max_workers} threads...")
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {}
for task in tasks:
if task[0] is None: # Skip invalid tasks
continue
future = executor.submit(clip_and_encode_audio, *task)
futures[future] = task[4] # segment_idx
for future in as_completed(futures):
try:
result = future.result()
results.append(result)
completed_count += 1
# Log progress every 100 segments or at completion
if completed_count % 100 == 0 or completed_count == len(futures):
print(f"Progress: {completed_count}/{len(futures)} segments processed ({completed_count*100//len(futures)}%)")
except Exception as e:
idx = futures[future]
results.append((idx, None, f"Processing error: {str(e)}"))
completed_count += 1
print(f"Error on segment {idx}: {e}")
print(f"✅ Completed processing all {len(futures)} valid segments")
# Sort by segment index to maintain order
results.sort(key=lambda x: x[0])
# Build output list with labels
audio_segments = []
for i, (idx, audio_src, error_msg) in enumerate(results):
seg = segments[idx] if idx < len(segments) else {}
start_time = seg.get('start_time', 'N/A')
end_time = seg.get('end_time', 'N/A')
speaker_id = seg.get('speaker_id', 'N/A')
segment_label = f"Segment {idx+1}: [{start_time:.2f}s - {end_time:.2f}s] Speaker {speaker_id}"
audio_segments.append((segment_label, audio_src, error_msg))
return audio_segments
except Exception as e:
print(f"Error loading audio file: {e}")
return []
# Global variable to store the ASR model
asr_model = None
# Global stop flag for generation
stop_generation_flag = False
class StopOnFlag(StoppingCriteria):
"""Custom stopping criteria that checks a global flag."""
def __call__(self, input_ids, scores, **kwargs):
global stop_generation_flag
return stop_generation_flag
def parse_time_to_seconds(val: Optional[str]) -> Optional[float]:
"""Parse seconds or hh:mm:ss to float seconds."""
if val is None:
return None
val = val.strip()
if not val:
return None
try:
return float(val)
except ValueError:
pass
if ":" in val:
parts = val.split(":")
if not all(p.strip().replace(".", "", 1).isdigit() for p in parts):
return None
parts = [float(p) for p in parts]
if len(parts) == 3:
h, m, s = parts
elif len(parts) == 2:
h = 0
m, s = parts
else:
return None
return h * 3600 + m * 60 + s
return None
def slice_audio_to_temp(
audio_data: np.ndarray,
sample_rate: int,
start_sec: Optional[float],
end_sec: Optional[float]
) -> Tuple[Optional[str], Optional[str]]:
"""Slice audio_data to [start_sec, end_sec) and write to a temp WAV file."""
n_samples = len(audio_data)
full_duration = n_samples / float(sample_rate)
start = 0.0 if start_sec is None else max(0.0, start_sec)
end = full_duration if end_sec is None else min(full_duration, end_sec)
if end <= start:
return None, f"Invalid time range: start={start:.2f}s, end={end:.2f}s"
start_idx = int(start * sample_rate)
end_idx = int(end * sample_rate)
segment = audio_data[start_idx:end_idx]
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
temp_file.close()
segment_int16 = (segment * 32768.0).astype(np.int16)
sf.write(temp_file.name, segment_int16, sample_rate, subtype='PCM_16')
return temp_file.name, None
def initialize_model(model_path: str, device: str = "cuda", attn_implementation: str = "flash_attention_2"):
"""Initialize the ASR model."""
global asr_model
try:
dtype = torch.bfloat16 if device != "cpu" else torch.float32
asr_model = VibeVoiceASRInference(
model_path=model_path,
device=device,
dtype=dtype,
attn_implementation=attn_implementation
)
return f"✅ Model loaded successfully from {model_path}"
except Exception as e:
import traceback
traceback.print_exc()
return f"❌ Error loading model: {str(e)}"
def transcribe_audio(
audio_input,
audio_path_input: str,
start_time_input: str,
end_time_input: str,
max_new_tokens: int,
temperature: float,
top_p: float,
do_sample: bool,
repetition_penalty: float = 1.0,
context_info: str = ""
) -> Generator[Tuple[str, str], None, None]:
"""
Transcribe audio and return results with audio segments (streaming version).
Args:
audio_input: Audio file path or tuple (sample_rate, audio_data)
max_new_tokens: Maximum tokens to generate
temperature: Temperature for sampling (0 for greedy)
top_p: Top-p for nucleus sampling
do_sample: Whether to use sampling
context_info: Optional context information (e.g., hotwords, speaker names, topics)
Yields:
Tuple of (raw_text, audio_segments_html)
"""
if asr_model is None:
yield "❌ Please load a model first!", ""
return
if not audio_path_input and audio_input is None:
yield "❌ Please provide audio input!", ""
return
try:
print("[INFO] Transcription requested")
start_sec = parse_time_to_seconds(start_time_input)
end_sec = parse_time_to_seconds(end_time_input)
print(f"[INFO] Parsed time range: start={start_sec}, end={end_sec}")
if (start_time_input and start_sec is None) or (end_time_input and end_sec is None):
yield "❌ Invalid time format. Use seconds or hh:mm:ss.", ""
return
audio_path = None
audio_array = None
sample_rate = None
if audio_path_input:
candidate = Path(audio_path_input.strip())
if not candidate.exists():
yield f"❌ Provided path does not exist: {candidate}", ""
return
audio_path = str(candidate)
print(f"[INFO] Using provided audio path: {audio_path}")
# Get audio file path (Gradio Audio component returns tuple (sample_rate, audio_data) or file path)
elif isinstance(audio_input, str):
audio_path = audio_input
print(f"[INFO] Using uploaded audio path: {audio_path}")
elif isinstance(audio_input, tuple):
# Audio from microphone: (sample_rate, audio_data)
sample_rate, audio_array = audio_input
print(f"[INFO] Received microphone audio with sample_rate={sample_rate}")
elif audio_path is None:
yield "❌ Invalid audio input format!", ""
return
# If slicing is requested, load and slice audio
if start_sec is not None or end_sec is not None:
print("[INFO] Slicing audio per requested time range")
if audio_array is None or sample_rate is None:
try:
audio_array, sample_rate = load_audio_use_ffmpeg(audio_path, resample=False)
print("[INFO] Loaded audio for slicing via ffmpeg")
except Exception as exc:
yield f"❌ Failed to load audio for slicing: {exc}", ""
return
sliced_path, err = slice_audio_to_temp(audio_array, sample_rate, start_sec, end_sec)
if err:
yield f"❌ {err}", ""
return
audio_path = sliced_path
print(f"[INFO] Sliced audio written to temp file: {audio_path}")
elif audio_array is not None and sample_rate is not None:
# no slicing but microphone input: write to temp file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
audio_path = temp_file.name
temp_file.close()
audio_data_int16 = (audio_array * 32768.0).astype(np.int16)
sf.write(audio_path, audio_data_int16, sample_rate, subtype='PCM_16')
print(f"[INFO] Microphone audio saved to temp file: {audio_path}")
# Create streamer for real-time output
streamer = TextIteratorStreamer(
asr_model.processor.tokenizer,
skip_prompt=True,
skip_special_tokens=True
)
# Store result in a mutable container for the thread
result_container = {"result": None, "error": None}
def run_transcription():
try:
result_container["result"] = asr_model.transcribe(
audio_path=audio_path,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
do_sample=do_sample,
repetition_penalty=repetition_penalty,
context_info=context_info if context_info and context_info.strip() else None,
streamer=streamer
)
except Exception as e:
result_container["error"] = str(e)
traceback.print_exc()
# Start transcription in background thread
print("[INFO] Starting model transcription (streaming mode)")
start_time = time.time()
transcription_thread = threading.Thread(target=run_transcription)
transcription_thread.start()
# Yield streaming output
generated_text = ""
token_count = 0
for new_text in streamer:
generated_text += new_text
token_count += 1
elapsed = time.time() - start_time
# Show streaming output with live stats, format for readability
formatted_text = generated_text.replace('},', '},\n')
streaming_output = f"--- 🔴 LIVE Streaming Output (tokens: {token_count}, time: {elapsed:.1f}s) ---\n{formatted_text}"
yield streaming_output, "<div style='padding: 20px; text-align: center; color: #6c757d;'>⏳ Generating transcription... Audio segments will appear after completion.</div>"
# Wait for thread to complete
transcription_thread.join()
if result_container["error"]:
yield f"❌ Error during transcription: {result_container['error']}", ""
return
result = result_container["result"]
generation_time = time.time() - start_time
# Get input token statistics
input_tokens = result.get('input_tokens', {})
speech_tokens = input_tokens.get('speech', 0)
text_tokens = input_tokens.get('text', 0)
padding_tokens = input_tokens.get('padding', 0)
total_input = input_tokens.get('total', 0)
# Format final raw output with input/output token stats
raw_output = f"--- ✅ Raw Output ---\n"
raw_output += f"📥 Input: {total_input} tokens (🎤 speech: {speech_tokens}, 📝 text: {text_tokens}, ⬜ pad: {padding_tokens})\n"
raw_output += f"📤 Output: {token_count} tokens | ⏱️ Time: {generation_time:.2f}s\n"
raw_output += f"---\n"
# Format raw text for better readability: add newline after each dict (},)
formatted_raw_text = result['raw_text'].replace('},', '},\n')
raw_output += formatted_raw_text
# Debug: print raw output to console
print(f"[DEBUG] Raw model output:")
print(f"[DEBUG] {result['raw_text']}")
print(f"[DEBUG] Found {len(result['segments'])} segments")
# Create audio segments with server-side encoding (low quality for minimal transfer)
# Using: 16kHz mono MP3 @ 32kbps = ~4KB per second of audio
audio_segments_html = ""
segments = result['segments']
if segments:
num_segments = len(segments)
print(f"[INFO] Creating per-segment audio clips ({num_segments} segments, 16kHz mono MP3 @ 32kbps)")
# Extract all audio segments efficiently (load audio only once)
audio_segments = extract_audio_segments(audio_path, segments)
print("[INFO] Completed creating audio clips")
# Calculate approximate total size
total_duration = sum(
(seg.get('end_time', 0) - seg.get('start_time', 0))
for seg in segments
if isinstance(seg.get('start_time'), (int, float)) and isinstance(seg.get('end_time'), (int, float))
)
approx_size_kb = total_duration * 4 # ~4KB per second at 32kbps
# Add CSS for theme-aware styling
theme_css = """
<style>
:root {
--segment-bg: #f8f9fa;
--segment-border: #e1e5e9;
--segment-text: #495057;
--segment-meta: #6c757d;
--content-bg: white;
--content-border: #007bff;
--warning-bg: #fff3cd;
--warning-border: #ffc107;
--warning-text: #856404;
}
@media (prefers-color-scheme: dark) {
:root {
--segment-bg: #2d3748;
--segment-border: #4a5568;
--segment-text: #e2e8f0;
--segment-meta: #a0aec0;
--content-bg: #1a202c;
--content-border: #4299e1;
--warning-bg: #744210;
--warning-border: #d69e2e;
--warning-text: #faf089;
}
}
.audio-segments-container {
max-height: 600px;
overflow-y: auto;
padding: 10px;
}
.audio-segment {
margin-bottom: 15px;
padding: 15px;
border: 2px solid var(--segment-border);
border-radius: 8px;
background-color: var(--segment-bg);
transition: all 0.3s ease;
}
.audio-segment:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.segment-header {
margin-bottom: 10px;
}
.segment-title {
margin: 0;
color: var(--segment-text);
font-size: 16px;
font-weight: 600;
}
.segment-meta {
margin-top: 5px;
font-size: 14px;
color: var(--segment-meta);
}
.segment-content {
margin-bottom: 10px;
padding: 12px;
background-color: var(--content-bg);
border-radius: 6px;
border-left: 4px solid var(--content-border);
color: var(--segment-text);
line-height: 1.5;
}
.segment-audio {
width: 100%;
margin-top: 10px;
border-radius: 4px;
}
.segment-warning {
margin-top: 10px;
padding: 10px;
background-color: var(--warning-bg);
border-radius: 4px;
border-left: 4px solid var(--warning-border);
color: var(--warning-text);
font-size: 13px;
}
.segments-title {
color: var(--segment-text);
margin-bottom: 10px;
}
.segments-description {
color: var(--segment-meta);
margin-bottom: 20px;
}
.size-badge {
display: inline-block;
background: linear-gradient(135deg, #6c757d, #495057);
color: white;
padding: 4px 10px;
border-radius: 12px;
font-size: 12px;
margin-left: 10px;
}
</style>
"""
audio_segments_html = theme_css
audio_segments_html += f"<div class='audio-segments-container'>"
# Add format info
format_info = "MP3 32kbps 16kHz mono" if HAS_PYDUB else "WAV 16kHz"
audio_segments_html += f"<h3 class='segments-title'>🔊 Audio Segments ({num_segments} segments)"
audio_segments_html += f"<span class='size-badge'>📦 ~{approx_size_kb:.0f}KB ({format_info})</span></h3>"
audio_segments_html += "<p class='segments-description'>🎵 Click the play button to listen to each segment directly!</p>"
for i, (label, audio_src, error_msg) in enumerate(audio_segments):
seg = segments[i] if i < len(segments) else {}
start_time = seg.get('start_time', 'N/A')
end_time = seg.get('end_time', 'N/A')
speaker_id = seg.get('speaker_id', 'N/A')
content = seg.get('text', '')
# Format times nicely
start_str = f"{start_time:.2f}" if isinstance(start_time, (int, float)) else str(start_time)
end_str = f"{end_time:.2f}" if isinstance(end_time, (int, float)) else str(end_time)
audio_segments_html += f"""
<div class='audio-segment'>
<div class='segment-header'>
<h4 class='segment-title'>Segment {i+1}</h4>
<div class='segment-meta'>
<strong>Time:</strong> [{start_str}s - {end_str}s] |
<strong>Speaker:</strong> {speaker_id}
</div>
</div>
<div class='segment-content'>
{content}
</div>
"""
if audio_src:
# Detect format from data URI
audio_type = 'audio/mp3' if 'audio/mp3' in audio_src else 'audio/wav'
audio_segments_html += f"""
<audio controls class='segment-audio' preload='none'>
<source src='{audio_src}' type='{audio_type}'>
Your browser does not support the audio element.
</audio>
"""
elif error_msg:
audio_segments_html += f"""
<div class='segment-warning'>
<small>❌ {error_msg}</small>
</div>
"""
else:
audio_segments_html += """
<div class='segment-warning'>
<small>Audio playback unavailable for this segment</small>
</div>
"""
audio_segments_html += "</div>"
audio_segments_html += "</div>"
else:
audio_segments_html = """
<style>
:root {
--no-segments-text: #6c757d;
}
@media (prefers-color-scheme: dark) {
:root {
--no-segments-text: #a0aec0;
}
}
.no-segments-container {
padding: 20px;
text-align: center;
color: var(--no-segments-text);
line-height: 1.6;
}
</style>
<div class='no-segments-container'>
<p>❌ No audio segments available.</p>
<p>This could happen if the model output doesn't contain valid time stamps.</p>
</div>
"""
# Final yield with complete results
yield raw_output, audio_segments_html
except Exception as e:
print(f"Error during transcription: {e}")
print(traceback.format_exc())
yield f"❌ Error during transcription: {str(e)}", ""
def create_gradio_interface(model_path: str, default_max_tokens: int = 8192, attn_implementation: str = "flash_attention_2"):
"""Create and launch Gradio interface.
Args:
model_path: Path to the model (HuggingFace format directory or model name)
default_max_tokens: Default value for max_new_tokens slider
attn_implementation: Attention implementation to use ('flash_attention_2', 'sdpa', 'eager')
"""
# Initialize model at startup
device = "cuda" if torch.cuda.is_available() else "cpu"
model_status = initialize_model(model_path, device, attn_implementation)
print(model_status)
# Exit if model loading failed
if model_status.startswith("❌"):
print("\n" + "="*80)
print("💥 FATAL ERROR: Model loading failed!")
print("="*80)
print("Cannot start demo without a valid model. Please check:")
print(" 1. Model path is correct")
print(" 2. Model files are not corrupted")
print(" 3. You have enough GPU memory")
print(" 4. CUDA is properly installed (if using GPU)")
print("="*80)
sys.exit(1)
# Custom CSS for Stop button styling
custom_css = """
#stop-btn {
background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
border: none !important;
color: white !important;
}
#stop-btn:hover {
background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%) !important;
}
"""
# Gradio 6.0+ moved theme/css to launch()
with gr.Blocks(title="VibeVoice ASR Demo") as demo:
gr.Markdown("# 🎙️ VibeVoice ASR Demo")
gr.Markdown("Upload audio files or record from microphone to get speech-to-text transcription with speaker diarization.")
gr.Markdown(f"**Model loaded from:** `{model_path}`")
with gr.Row():
with gr.Column(scale=1):
# Generation parameters
gr.Markdown("## ⚙️ Generation Parameters")
max_tokens_slider = gr.Slider(
minimum=4096,
maximum=65536,
value=default_max_tokens,
step=4096,
label="Max New Tokens"
)
# Sampling parameters
gr.Markdown("### 🎲 Sampling")
do_sample_checkbox = gr.Checkbox(
value=False,
label="Enable Sampling",
info="Enable random sampling instead of deterministic decoding"
)
with gr.Column(visible=False) as sampling_params:
temperature_slider = gr.Slider(
minimum=0.0,
maximum=2.0,
value=0.0,
step=0.1,
label="Temperature",
info="0 = greedy, higher = more random"
)
top_p_slider = gr.Slider(
minimum=0.0,
maximum=1.0,
value=1.0,
step=0.05,
label="Top-p (Nucleus Sampling)",
info="1.0 = no filtering"
)
# Repetition penalty (works with both greedy and sampling)
repetition_penalty_slider = gr.Slider(
minimum=1.0,
maximum=1.2,
value=1.0,
step=0.01,
label="Repetition Penalty",
info="1.0 = no penalty, higher = less repetition (works with greedy & sampling)"
)
# Context information section
gr.Markdown("## 📋 Context Info (Optional)")
context_info_input = gr.Textbox(
label="Context Information",
placeholder="Enter hotwords, speaker names, topics, or other context to help transcription...\nExample:\nJohn Smith\nMachine Learning\nOpenAI",
lines=4,
max_lines=8,
interactive=True,
info="Provide context like proper nouns, technical terms, or speaker names to improve accuracy"
)
with gr.Column(scale=2):
# Audio input section
gr.Markdown("## 🎵 Audio Input")
audio_input = gr.Audio(
label="Upload Audio File or Record from Microphone",
sources=["upload", "microphone"],
type="filepath",
interactive=True,
buttons=["download"]
)
with gr.Accordion("📂 Advanced: Remote Path & Time Slicing", open=False):
audio_path_input = gr.Textbox(
label="Audio path (optional)",
placeholder="Enter remote audio file path",
lines=1
)
with gr.Row():
start_time_input = gr.Textbox(
label="Start time",
placeholder="e.g., 0 or 00:00:00",
lines=1,
info="Leave empty to start from the beginning"
)
end_time_input = gr.Textbox(
label="End time",
placeholder="e.g., 30.5 or 00:00:30.5",
lines=1,
info="Leave empty to use full length"
)
with gr.Row():
transcribe_button = gr.Button("🎯 Transcribe", variant="primary", size="lg", scale=3)
stop_button = gr.Button("⏹️ Stop", variant="secondary", size="lg", scale=1, elem_id="stop-btn")
# Results section
gr.Markdown("## 📝 Results")
with gr.Tabs():
with gr.TabItem("Raw Output"):
raw_output = gr.Textbox(
label="Raw Transcription Output",
lines=8,
max_lines=20,
interactive=False
)
with gr.TabItem("Audio Segments"):
audio_segments_output = gr.HTML(
label="Play individual segments to verify accuracy"
)
# Event handlers
do_sample_checkbox.change(
fn=lambda x: gr.update(visible=x),
inputs=[do_sample_checkbox],
outputs=[sampling_params]
)
def reset_stop_flag():
"""Reset stop flag before starting transcription."""
global stop_generation_flag
stop_generation_flag = False
def set_stop_flag():
"""Set stop flag to interrupt generation."""
global stop_generation_flag
stop_generation_flag = True
return "⏹️ Stop requested..."
transcribe_button.click(
fn=reset_stop_flag,
inputs=[],
outputs=[],
queue=False
).then(
fn=transcribe_audio,
inputs=[
audio_input,
audio_path_input,
start_time_input,
end_time_input,
max_tokens_slider,
temperature_slider,
top_p_slider,
do_sample_checkbox,
repetition_penalty_slider,
context_info_input
],
outputs=[raw_output, audio_segments_output]
)
stop_button.click(
fn=set_stop_flag,
inputs=[],
outputs=[raw_output],
queue=False
)
# Add examples
gr.Markdown("## 📋 Instructions")
gr.Markdown(f"""
1. **Upload Audio**: Use the audio component to upload a file or record from microphone
- **Supported formats**: {', '.join(sorted(set([ext.lower() for ext in COMMON_AUDIO_EXTS])))}
- Optionally set **Start/End time** (seconds or hh:mm:ss) to clip before transcription
2. **Context Info (Optional)**: Provide context to improve transcription accuracy
- Add hotwords, proper nouns, speaker names, or technical terms
- One item per line or comma-separated
- Examples: "John Smith", "OpenAI", "machine learning"
3. **Adjust Parameters**: Configure generation parameters as needed
4. **Transcribe**: Click "Transcribe" to get results
5. **Review Results**:
- **Raw Output**: View the model's original output
- **Audio Segments**: Play individual segments directly to verify accuracy
**Audio Segments**: Each segment shows the time range, speaker ID, transcribed content, and an embedded audio player for immediate verification.
""")
return demo, custom_css
def main():
parser = argparse.ArgumentParser(description="VibeVoice ASR Gradio Demo")
parser.add_argument(
"--model_path",
type=str,
default="microsoft/VibeVoice-ASR",
help="Path to the model (HuggingFace format directory or model name)"
)
parser.add_argument(
"--attn_implementation",
type=str,
default="flash_attention_2",
help="Attention implementation to use (default: flash_attention_2)"
)
parser.add_argument(
"--max_new_tokens",
type=int,
default=32768,
help="Default max new tokens for generation (default: 32768)"
)
parser.add_argument(
"--host",
type=str,
default="0.0.0.0",
help="Host to bind the server to"
)
parser.add_argument(
"--port",
type=int,
default=7860,
help="Port to bind the server to"
)
parser.add_argument(
"--share",
action="store_true",
help="Create a public link"
)
args = parser.parse_args()
# Create and launch interface
demo, custom_css = create_gradio_interface(
model_path=args.model_path,
default_max_tokens=args.max_new_tokens,
attn_implementation=args.attn_implementation
)
print(f"🚀 Starting VibeVoice ASR Demo...")
print(f"📍 Server will be available at: http://{args.host}:{args.port}")
# Gradio 6.0+ moved theme/css to launch()
launch_kwargs = {
"server_name": args.host,
"server_port": args.port,
"share": args.share,
"show_error": True,
"theme": gr.themes.Soft(),
"css": custom_css,
}
# Enable queue for concurrent request handling
demo.queue(default_concurrency_limit=3)
demo.launch(**launch_kwargs)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "demo/vibevoice_asr_gradio_demo.py",
"license": "MIT License",
"lines": 1012,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:demo/vibevoice_asr_inference_from_file.py | #!/usr/bin/env python
"""
VibeVoice ASR Batch Inference Demo Script
This script supports batch inference for ASR model and compares results
between batch processing and single-sample processing.
"""
import os
import sys
import torch
import numpy as np
from pathlib import Path
import argparse
import time
import json
import re
from typing import List, Dict, Any, Optional
from functools import wraps
from vibevoice.modular.modeling_vibevoice_asr import VibeVoiceASRForConditionalGeneration
from vibevoice.processor.vibevoice_asr_processor import VibeVoiceASRProcessor
class VibeVoiceASRBatchInference:
"""Batch inference wrapper for VibeVoice ASR model."""
def __init__(
self,
model_path: str,
device: str = "cuda",
dtype: torch.dtype = torch.bfloat16,
attn_implementation: str = "sdpa"
):
"""
Initialize the ASR batch inference pipeline.
Args:
model_path: Path to the pretrained model
device: Device to run inference on (cuda, mps, xpu, cpu, auto)
dtype: Data type for model weights
attn_implementation: Attention implementation to use ('flash_attention_2', 'sdpa', 'eager')
"""
print(f"Loading VibeVoice ASR model from {model_path}")
# Load processor
self.processor = VibeVoiceASRProcessor.from_pretrained(
model_path,
language_model_pretrained_name="Qwen/Qwen2.5-7B"
)
# Load model with specified attention implementation
print(f"Using attention implementation: {attn_implementation}")
self.model = VibeVoiceASRForConditionalGeneration.from_pretrained(
model_path,
dtype=dtype,
device_map=device if device == "auto" else None,
attn_implementation=attn_implementation,
trust_remote_code=True
)
if device != "auto":
self.model = self.model.to(device)
self.device = device if device != "auto" else next(self.model.parameters()).device
self.dtype = dtype
self.model.eval()
print(f"Model loaded successfully on {self.device}")
def _prepare_generation_config(
self,
max_new_tokens: int = 512,
temperature: float = 0.0,
top_p: float = 0.9,
do_sample: bool = True,
num_beams: int = 1,
) -> dict:
"""Prepare generation configuration."""
config = {
"max_new_tokens": max_new_tokens,
"pad_token_id": self.processor.pad_id,
"eos_token_id": self.processor.tokenizer.eos_token_id,
}
# Beam search vs sampling
if num_beams > 1:
config["num_beams"] = num_beams
config["do_sample"] = False # Beam search doesn't use sampling
else:
config["do_sample"] = do_sample
# Only set temperature and top_p when sampling is enabled
if do_sample:
config["temperature"] = temperature
config["top_p"] = top_p
return config
def transcribe_batch(
self,
audio_inputs: List,
max_new_tokens: int = 512,
temperature: float = 0.0,
top_p: float = 1.0,
do_sample: bool = True,
num_beams: int = 1,
) -> List[Dict[str, Any]]:
"""
Transcribe multiple audio files/arrays in a single batch.
Args:
audio_inputs: List of audio file paths or (array, sampling_rate) tuples
max_new_tokens: Maximum tokens to generate
temperature: Temperature for sampling
top_p: Top-p for nucleus sampling
do_sample: Whether to use sampling
Returns:
List of transcription results
"""
if len(audio_inputs) == 0:
return []
batch_size = len(audio_inputs)
print(f"\nProcessing batch of {batch_size} audio(s)...")
# Process all audio together
inputs = self.processor(
audio=audio_inputs,
sampling_rate=None,
return_tensors="pt",
padding=True,
add_generation_prompt=True
)
# Move to device
inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
for k, v in inputs.items()}
# Print batch info
print(f" Input IDs shape: {inputs['input_ids'].shape}")
print(f" Speech tensors shape: {inputs['speech_tensors'].shape}")
print(f" Attention mask shape: {inputs['attention_mask'].shape}")
# Generate
generation_config = self._prepare_generation_config(
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
do_sample=do_sample,
num_beams=num_beams,
)
start_time = time.time()
with torch.no_grad():
output_ids = self.model.generate(
**inputs,
**generation_config
)
generation_time = time.time() - start_time
# Decode outputs for each sample in the batch
results = []
input_length = inputs['input_ids'].shape[1]
for i, audio_input in enumerate(audio_inputs):
# Get generated tokens for this sample (excluding input tokens)
generated_ids = output_ids[i, input_length:]
# Remove padding tokens from the end
# Find the first eos_token or pad_token
eos_positions = (generated_ids == self.processor.tokenizer.eos_token_id).nonzero(as_tuple=True)[0]
if len(eos_positions) > 0:
generated_ids = generated_ids[:eos_positions[0] + 1]
generated_text = self.processor.decode(generated_ids, skip_special_tokens=True)
# Parse structured output
try:
transcription_segments = self.processor.post_process_transcription(generated_text)
except Exception as e:
print(f"Warning: Failed to parse structured output: {e}")
transcription_segments = []
# Get file name based on input type
if isinstance(audio_input, str):
file_name = audio_input
elif isinstance(audio_input, dict) and 'id' in audio_input:
file_name = audio_input['id']
else:
file_name = f"audio_{i}"
results.append({
"file": file_name,
"raw_text": generated_text,
"segments": transcription_segments,
"generation_time": generation_time / batch_size,
})
print(f" Total generation time: {generation_time:.2f}s")
print(f" Average time per sample: {generation_time/batch_size:.2f}s")
return results
def transcribe_with_batching(
self,
audio_inputs: List,
batch_size: int = 4,
max_new_tokens: int = 512,
temperature: float = 0.0,
top_p: float = 1.0,
do_sample: bool = True,
num_beams: int = 1,
) -> List[Dict[str, Any]]:
"""
Transcribe multiple audio files/arrays with automatic batching.
Args:
audio_inputs: List of audio file paths or (array, sampling_rate) tuples
batch_size: Number of samples per batch
max_new_tokens: Maximum tokens to generate
temperature: Temperature for sampling
top_p: Top-p for nucleus sampling
do_sample: Whether to use sampling
Returns:
List of transcription results
"""
all_results = []
# Process in batches
for i in range(0, len(audio_inputs), batch_size):
batch_inputs = audio_inputs[i:i + batch_size]
print(f"\n{'='*60}")
print(f"Processing batch {i//batch_size + 1}/{(len(audio_inputs) + batch_size - 1)//batch_size}")
batch_results = self.transcribe_batch(
batch_inputs,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
do_sample=do_sample,
num_beams=num_beams,
)
all_results.extend(batch_results)
return all_results
def print_result(result: Dict[str, Any]):
"""Pretty print a single transcription result."""
print(f"\nFile: {result['file']}")
print(f"Generation Time: {result['generation_time']:.2f}s")
print(f"\n--- Raw Output ---")
print(result['raw_text'][:500] + "..." if len(result['raw_text']) > 500 else result['raw_text'])
if result['segments']:
print(f"\n--- Structured Output ({len(result['segments'])} segments) ---")
for seg in result['segments'][:50]: # Show first 50 segments
print(f"[{seg.get('start_time', 'N/A')} - {seg.get('end_time', 'N/A')}] "
f"Speaker {seg.get('speaker_id', 'N/A')}: {seg.get('text', '')}...")
if len(result['segments']) > 50:
print(f" ... and {len(result['segments']) - 50} more segments")
def load_dataset_and_concatenate(
dataset_name: str,
split: str,
max_duration: float,
num_audios: int,
target_sr: int = 24000
) -> Optional[List[np.ndarray]]:
"""
Load a HuggingFace dataset and concatenate audio samples into long audio chunks.
(Note, just for demo purpose, not for benchmark evaluation)
Args:
dataset_name: HuggingFace dataset name (e.g., 'openslr/librispeech_asr')
split: Dataset split to use (e.g., 'test', 'test.other')
max_duration: Maximum duration in seconds for each concatenated audio
num_audios: Number of concatenated audios to create
target_sr: Target sample rate (default: 24000)
Returns:
List of concatenated audio arrays, or None if loading fails
"""
try:
from datasets import load_dataset
import torchcodec # just for decode audio in datasets
except ImportError:
print("Please install it with: pip install datasets torchcodec")
return None
print(f"\nLoading dataset: {dataset_name} (split: {split})")
print(f"Will create {num_audios} concatenated audio(s), each up to {max_duration:.1f}s ({max_duration/3600:.2f} hours)")
try:
# Use streaming to avoid downloading the entire dataset
dataset = load_dataset(dataset_name, split=split, streaming=True)
print(f"Dataset loaded in streaming mode")
concatenated_audios = [] # List of concatenated audio metadata
# Create multiple concatenated audios based on num_audios
current_chunks = []
current_duration = 0.0
current_samples_used = 0
sample_idx = 0
for sample in dataset:
if len(concatenated_audios) >= num_audios:
break
if 'audio' not in sample:
continue
audio_data = sample['audio']
audio_array = audio_data['array']
sr = audio_data['sampling_rate']
# Resample if needed
if sr != target_sr:
duration = len(audio_array) / sr
new_length = int(duration * target_sr)
audio_array = np.interp(
np.linspace(0, len(audio_array) - 1, new_length),
np.arange(len(audio_array)),
audio_array
)
chunk_duration = len(audio_array) / target_sr
# Check if adding this chunk exceeds max_duration
if current_duration + chunk_duration > max_duration:
remaining_duration = max_duration - current_duration
if remaining_duration > 0.5: # Only add if > 0.5s remaining
samples_to_take = int(remaining_duration * target_sr)
current_chunks.append(audio_array[:samples_to_take])
current_duration += remaining_duration
current_samples_used += 1
# Save current concatenated audio and start a new one
if current_chunks:
concatenated_audios.append({
'array': np.concatenate(current_chunks),
'duration': current_duration,
'samples_used': current_samples_used,
})
print(f" Created audio {len(concatenated_audios)}: {current_duration:.1f}s from {current_samples_used} samples")
# Reset for next concatenated audio
current_chunks = []
current_duration = 0.0
current_samples_used = 0
if len(concatenated_audios) >= num_audios:
break
current_chunks.append(audio_array)
current_duration += chunk_duration
current_samples_used += 1
sample_idx += 1
if sample_idx % 100 == 0:
print(f" Processed {sample_idx} samples...")
# Don't forget the last batch if it has content
if current_chunks and len(concatenated_audios) < num_audios:
concatenated_audios.append({
'array': np.concatenate(current_chunks),
'duration': current_duration,
'samples_used': current_samples_used,
})
print(f" Created audio {len(concatenated_audios)}: {current_duration:.1f}s from {current_samples_used} samples")
if not concatenated_audios:
print("Warning: No audio samples found in dataset")
return None
# Extract arrays and print summary
result = [a['array'] for a in concatenated_audios]
total_duration = sum(a['duration'] for a in concatenated_audios)
total_samples = sum(a['samples_used'] for a in concatenated_audios)
print(f"\nCreated {len(result)} concatenated audio(s), total {total_duration:.1f}s ({total_duration/60:.1f} min) from {total_samples} samples")
return result
except Exception as e:
print(f"Error loading dataset: {e}")
import traceback
traceback.print_exc()
return None
def main():
parser = argparse.ArgumentParser(description="VibeVoice ASR Batch Inference Demo")
parser.add_argument(
"--model_path",
type=str,
default="",
help="Path to the model checkpoint"
)
parser.add_argument(
"--audio_files",
type=str,
nargs='+',
required=False,
help="Paths to audio files for transcription"
)
parser.add_argument(
"--audio_dir",
type=str,
required=False,
help="Directory containing audio files for batch transcription"
)
parser.add_argument(
"--dataset",
type=str,
required=False,
help="HuggingFace dataset name (e.g., 'openslr/librispeech_asr')"
)
parser.add_argument(
"--split",
type=str,
default="test",
help="Dataset split to use (e.g., 'test', 'test.other', 'test.clean')"
)
parser.add_argument(
"--max_duration",
type=float,
default=3600.0,
help="Maximum duration in seconds for concatenated dataset audio (default: 3600 = 1 hour)"
)
parser.add_argument(
"--batch_size",
type=int,
default=2,
help="Batch size for processing multiple files"
)
parser.add_argument(
"--device",
type=str,
default="cuda" if torch.cuda.is_available() else ("xpu" if torch.backends.xpu.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu") ),
choices=["cuda", "cpu", "mps","xpu", "auto"],
help="Device to run inference on"
)
parser.add_argument(
"--max_new_tokens",
type=int,
default=32768,
help="Maximum number of tokens to generate"
)
parser.add_argument(
"--temperature",
type=float,
default=0.0,
help="Temperature for sampling (0 = greedy decoding)"
)
parser.add_argument(
"--top_p",
type=float,
default=1.0,
help="Top-p for nucleus sampling"
)
parser.add_argument(
"--num_beams",
type=int,
default=1,
help="Number of beams for beam search. Use 1 for greedy/sampling"
)
parser.add_argument(
"--attn_implementation",
type=str,
default="auto",
choices=["flash_attention_2", "sdpa", "eager", "auto"],
help="Attention implementation to use. 'auto' will select the best available for your device (flash_attention_2 for CUDA, sdpa for MPS/CPU/XPU)"
)
args = parser.parse_args()
# Auto-detect best attention implementation based on device
if args.attn_implementation == "auto":
if args.device == "cuda" and torch.cuda.is_available():
try:
import flash_attn
args.attn_implementation = "flash_attention_2"
except ImportError:
print("flash_attn not installed, falling back to sdpa")
args.attn_implementation = "sdpa"
else:
# MPS/XPU/CPU don't support flash_attention_2
args.attn_implementation = "sdpa"
print(f"Auto-detected attention implementation: {args.attn_implementation}")
# Collect audio files
audio_files = []
concatenated_audio = None # For storing concatenated dataset audio
if args.audio_files:
audio_files.extend(args.audio_files)
if args.audio_dir:
import glob
for ext in ["*.wav", "*.mp3", "*.flac", "*.mp4", "*.m4a", "*.webm"]:
audio_files.extend(glob.glob(os.path.join(args.audio_dir, ext)))
if args.dataset:
concatenated_audio = load_dataset_and_concatenate(
dataset_name=args.dataset,
split=args.split,
max_duration=args.max_duration,
num_audios=args.batch_size,
)
if concatenated_audio is None:
return
if len(audio_files) == 0 and concatenated_audio is None:
print("No audio files provided. Please specify --audio_files, --audio_dir, or --dataset.")
return
if audio_files:
print(f"\nAudio files to process ({len(audio_files)}):")
for f in audio_files:
print(f" - {f}")
if concatenated_audio:
print(f"\nConcatenated dataset audios: {len(concatenated_audio)} audio(s)")
# Initialize model
# Handle MPS device and dtype
if args.device == "mps":
model_dtype = torch.float32 # MPS works better with float32
elif args.device == "xpu":
model_dtype = torch.float32
elif args.device == "cpu":
model_dtype = torch.float32
else:
model_dtype = torch.bfloat16
asr = VibeVoiceASRBatchInference(
model_path=args.model_path,
device=args.device,
dtype=model_dtype,
attn_implementation=args.attn_implementation
)
# If temperature is 0, use greedy decoding (no sampling)
do_sample = args.temperature > 0
# Combine all audio inputs
all_audio_inputs = audio_files + (concatenated_audio or [])
print("\n" + "="*80)
print(f"Processing {len(all_audio_inputs)} audio(s)")
print("="*80)
all_results = asr.transcribe_with_batching(
all_audio_inputs,
batch_size=args.batch_size,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
top_p=args.top_p,
do_sample=do_sample,
num_beams=args.num_beams,
)
# Print results
print("\n" + "="*80)
print("Results")
print("="*80)
for result in all_results:
print("\n" + "-"*60)
print_result(result)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "demo/vibevoice_asr_inference_from_file.py",
"license": "MIT License",
"lines": 491,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modeling_vibevoice.py | # copied from https://github.com/vibevoice-community/VibeVoice/blob/main/vibevoice/modular/modeling_vibevoice.py
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union, Callable
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from transformers.models.auto import AutoModel, AutoModelForCausalLM
from transformers.activations import ACT2FN
from transformers.modeling_outputs import CausalLMOutput, BaseModelOutputWithPast, ModelOutput
from transformers.models.llama.modeling_llama import LlamaRMSNorm
from transformers import modeling_utils
from transformers.modeling_utils import PreTrainedModel
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.utils import logging
from .modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache, VibeVoiceAcousticTokenizerModel, VibeVoiceSemanticTokenizerModel
from .modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler
from .configuration_vibevoice import VibeVoiceConfig
logger = logging.get_logger(__name__)
if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
@dataclass
class VibeVoiceCausalLMOutputWithPast(ModelOutput):
loss: Optional[torch.FloatTensor] = None
diffusion_loss: Optional[torch.FloatTensor] = None
speech_token_num: Optional[int] = None
logits: torch.FloatTensor = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
@dataclass
class VibeVoiceGenerationOutput(ModelOutput):
"""
Output type for VibeVoice generation.
Args:
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
The generated sequences.
speech_outputs (`List[torch.FloatTensor]`, *optional*):
List of generated speech waveforms or latents for each speech segment.
"""
sequences: torch.LongTensor = None
speech_outputs: Optional[List[torch.FloatTensor]] = None
class SpeechConnector(nn.Module):
def __init__(self, input_dim, output_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, output_dim)
self.norm = LlamaRMSNorm(output_dim, eps=1e-6)
self.fc2 = nn.Linear(output_dim, output_dim)
def forward(self, features, **kwargs):
x = self.fc1(features)
x = self.norm(x)
x = self.fc2(x)
return x
# @auto_docstring
class VibeVoicePreTrainedModel(PreTrainedModel):
config_class = VibeVoiceConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_skip_keys_device_placement = "past_key_values"
_supports_cache_class = True
_supports_flash_attn_2 = True
_supports_sdpa = True
_supports_quantized_cache = True
_supports_static_cache = True
_supports_attention_backend = True
def _init_weights(self, module):
if isinstance(module, VibeVoiceDiffusionHead):
module.initialize_weights()
return
# Use the language model's initializer_range if available
if hasattr(self.config, 'language_model_config') and hasattr(self.config.language_model_config, 'initializer_range'):
std = self.config.language_model_config.initializer_range
elif hasattr(self.config, 'decoder_config') and hasattr(self.config.decoder_config, 'initializer_range'):
std = self.config.decoder_config.initializer_range
else:
std = 0.02 # Default value
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.weight.data.fill_(1.0)
module.bias.data.zero_()
# @auto_docstring
class VibeVoiceModel(VibeVoicePreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, 'torch_dtype') and config.torch_dtype is not None:
if isinstance(config.torch_dtype, str):
dtype = getattr(torch, config.torch_dtype)
else:
dtype = config.torch_dtype
else:
dtype = torch.float32
# Initialize Qwen2 model for language modeling
lm_config = config.decoder_config
self.language_model = AutoModel.from_config(lm_config)
# Initialize speech components if needed
self.acoustic_tokenizer = AutoModel.from_config(config.acoustic_tokenizer_config).to(dtype)
self.semantic_tokenizer = AutoModel.from_config(config.semantic_tokenizer_config).to(dtype)
self.acoustic_connector = SpeechConnector(config.acoustic_vae_dim, lm_config.hidden_size).to(dtype)
self.semantic_connector = SpeechConnector(config.semantic_vae_dim, lm_config.hidden_size).to(dtype)
# Register scaling factors as buffers - use 1D tensors for FSDP compatibility
self.register_buffer('speech_scaling_factor', torch.tensor(float('nan')))
self.register_buffer('speech_bias_factor', torch.tensor(float('nan')))
# Initialize prediction head for speech generation
self.prediction_head = AutoModel.from_config(config.diffusion_head_config).to(dtype)
# Initialize noise scheduler
self.noise_scheduler = DPMSolverMultistepScheduler(
num_train_timesteps=config.diffusion_head_config.ddpm_num_steps,
beta_schedule=config.diffusion_head_config.ddpm_beta_schedule,
prediction_type=config.diffusion_head_config.prediction_type
)
def get_input_embeddings(self):
if hasattr(self.language_model, 'embed_tokens'):
# If the language model has an embed_tokens attribute, return it
return self.language_model.embed_tokens
for name, attr in self.language_model.fullmap.items(): # parallel by nnscaler, the name is changed
if attr.orig_name == 'embed_tokens.weight':
return getattr(self.language_model, name)
assert False, 'should not arrive here'
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def set_speech_tokenizers(self, acoustic_tokenizer=None, semantic_tokenizer=None):
"""Set the speech tokenizers used for encoding and decoding speech."""
self.acoustic_tokenizer = acoustic_tokenizer
self.semantic_tokenizer = semantic_tokenizer
# Reset the encoder to evaluation mode
if self.acoustic_tokenizer is not None:
self.acoustic_tokenizer.eval()
if self.semantic_tokenizer is not None:
self.semantic_tokenizer.eval()
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> Union[Tuple, BaseModelOutputWithPast]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Forward through language model
outputs = self.language_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)
if not return_dict:
return outputs
return BaseModelOutputWithPast(
last_hidden_state=outputs.last_hidden_state,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class VibeVoiceForConditionalGeneration(VibeVoicePreTrainedModel):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
def __init__(self, config):
super().__init__(config)
self.model = VibeVoiceModel(config)
self.vocab_size = config.decoder_config.vocab_size
self.lm_head = nn.Linear(config.decoder_config.hidden_size, self.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def get_output_embeddings(self):
return self.lm_head
def set_decoder(self, decoder):
self.model.language_model = decoder
def get_decoder(self):
return self.model.language_model
def tie_weights(self):
"""
Tie the weights between the input embeddings and the output embeddings.
"""
if getattr(self.config.decoder_config, 'tie_word_embeddings', False):
# The standard PreTrainedModel method will handle the tying.
# It typically does a simple parameter object assignment, which is
# CORRECT to do BEFORE FSDP wraps the model.
output_embeddings = self.get_output_embeddings()
input_embeddings = self.get_input_embeddings()
if hasattr(input_embeddings, 'weight'):
output_embeddings.weight = input_embeddings.weight
else:
# maybe returned input_embeddings a tensor directly
output_embeddings.weight = input_embeddings
if getattr(output_embeddings, "bias", None) is not None:
output_embeddings.bias.data = nn.functional.pad(
output_embeddings.bias.data,
(0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0]),
"constant",
0,
)
print("Tied input and output embeddings using standard assignment.")
else:
print("tie_word_embeddings is False, not tying weights.")
# Also, ensure set_output_embeddings is safe, though your implementation looks okay.
# The key is to avoid calling it after accelerator.prepare().
def set_output_embeddings(self, new_embeddings):
# Your current implementation using data.copy_ is good practice,
# but the best way is to not call this after prepare().
self.lm_head = new_embeddings
def forward_speech_features(
self,
speech_tensors=None,
speech_masks=None,
speech_type="audio",
return_unmask=False
):
if speech_tensors is None:
# Use config to get vae_dim instead of non-existent self.args
vae_dim = self.config.acoustic_tokenizer_config.vae_dim
audio_features = torch.zeros(1, 1, vae_dim).to(self.get_input_embeddings().weight)
connect_features = self.model.acoustic_connector(audio_features)
return audio_features, connect_features
else:
with torch.no_grad():
if speech_type == "audio":
with torch.no_grad():
frames = self.model.acoustic_tokenizer.encode(speech_tensors.unsqueeze(1))[0][0]
audio_tokens = frames.sample(self.model.acoustic_tokenizer.std_dist_type)[0]
elif speech_type == "vae":
# Use config to get vae_dim instead of non-existent self.args
vae_dim = self.config.acoustic_tokenizer_config.vae_dim
speech_mode = speech_tensors.reshape(speech_tensors.size(0), -1, vae_dim)
# gaussian sample from the speech_mode
batch_size = speech_mode.size(0)
value = self.model.acoustic_tokenizer.fix_std / 0.8
std = torch.randn(batch_size, dtype=speech_mode.dtype, device=speech_mode.device) * value
std = std.view(-1, *[1] * (speech_mode.dim() - 1))
audio_tokens = speech_mode + std * torch.randn(speech_mode.shape).to(speech_mode)
else:
raise NotImplementedError(f"Speech type {speech_type} not implemented")
if torch.isnan(self.model.speech_scaling_factor) or torch.isnan(self.model.speech_bias_factor):
scaling_factor = 1. / audio_tokens[speech_masks].flatten().std()
bias_factor = -audio_tokens[speech_masks].flatten().mean()
# Only use distributed operations if the process group is initialized
if dist.is_available() and dist.is_initialized():
dist.all_reduce(scaling_factor, op=dist.ReduceOp.SUM)
dist.all_reduce(bias_factor, op=dist.ReduceOp.SUM)
world_size = dist.get_world_size()
self.model.speech_scaling_factor.copy_(scaling_factor / world_size)
self.model.speech_bias_factor.copy_(bias_factor / world_size)
print(f"Speech scaling factor (distributed): {self.model.speech_scaling_factor}, bias factor: {self.model.speech_bias_factor}", flush=True)
else:
# Single process case
self.model.speech_scaling_factor.copy_(scaling_factor)
self.model.speech_bias_factor.copy_(bias_factor)
print(f"Speech scaling factor (single process): {self.model.speech_scaling_factor}, bias factor: {self.model.speech_bias_factor}", flush=True)
audio_features = (audio_tokens + self.model.speech_bias_factor) * self.model.speech_scaling_factor
connect_features = self.model.acoustic_connector(audio_features)
if return_unmask:
return audio_features, connect_features
return audio_features[speech_masks], connect_features[speech_masks]
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = False,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
# New arguments for speech processing and loss calculation
speech_tensors: Optional[torch.FloatTensor] = None,
speech_masks: Optional[torch.BoolTensor] = None,
speeches_loss_input: Optional[torch.FloatTensor] = None,
speech_semantic_tensors: Optional[torch.FloatTensor] = None,
acoustic_input_mask: Optional[torch.BoolTensor] = None,
acoustic_loss_mask: Optional[torch.BoolTensor] = None,
ddpm_batch_mul: int = 1,
**kwargs: Optional[Dict[str, Union[torch.Tensor, str]]],
) -> Union[Tuple, VibeVoiceCausalLMOutputWithPast]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
x = self.get_input_embeddings()(input_ids)
semantic_speech_all_connect_features = self.model.semantic_connector(speech_semantic_tensors)
if speeches_loss_input is not None:
# only part audio need diffuse
speech_all_features, speech_all_connect_features = self.forward_speech_features(
speech_tensors=speech_tensors.type_as(x) if speech_tensors is not None else None,
speech_masks=speech_masks,
speech_type=kwargs.get("speech_type", "audio"),
return_unmask=True
)
if speech_tensors is not None:
if semantic_speech_all_connect_features is not None:
x[acoustic_input_mask] = (
speech_all_connect_features[speech_masks]
+ semantic_speech_all_connect_features[speech_masks]
)
else:
x[acoustic_input_mask] = speech_all_connect_features[speech_masks]
# Select only the target segments' latents for diffusion loss.
# Both masks are [num_segments, max_latent_len]; using 2D mask on [B,T,D] selects [N_true, D].
target_latent_mask = speeches_loss_input & speech_masks
speech_features = speech_all_features[target_latent_mask]
speech_connect_features = speech_all_connect_features[target_latent_mask]
else:
speech_features, speech_connect_features = self.forward_speech_features(
speech_tensors=speech_tensors.type_as(x) if speech_tensors is not None else None,
speech_masks=speech_masks,
speech_type=kwargs.get("speech_type", "audio"),
)
if speech_tensors is not None:
x[acoustic_input_mask] = speech_connect_features
outputs = self.model(
input_ids=None,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=x,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=False,
return_dict=return_dict,
cache_position=cache_position,
)
hidden_states = outputs.last_hidden_state
logits = self.lm_head(hidden_states)
# logits = logits.float()
loss = None
if labels is not None:
# The custom CE loss with masking is calculated in the training script.
# We leave the standard loss calculation here as None.
pass
# --- Diffusion Loss Calculation ---
diffusion_loss = None
# This block is executed only if we are in a context that involves speech.
if speech_tensors is not None and acoustic_loss_mask.sum().item() > 0:
condition_features = hidden_states[acoustic_loss_mask]
speech_len, latent_size = speech_features.shape
noise = torch.randn(
(speech_len * ddpm_batch_mul, latent_size),
device=hidden_states.device,
dtype=hidden_states.dtype
)
timesteps = torch.multinomial(
torch.ones(self.config.diffusion_head_config.ddpm_num_steps),
speech_len * ddpm_batch_mul,
replacement=True,
).to(hidden_states.device)
speech_features_repeated = speech_features.repeat_interleave(ddpm_batch_mul, dim=0)
condition_features_repeated = condition_features.repeat_interleave(ddpm_batch_mul, dim=0)
noisy_speech_features = self.model.noise_scheduler.add_noise(
speech_features_repeated, noise, timesteps
)
model_output = self.model.prediction_head(
noisy_speech_features,
timesteps.type_as(x),
condition_features_repeated
)
prediction_type = self.config.diffusion_head_config.prediction_type
if prediction_type == "epsilon":
target_for_loss = noise
elif prediction_type == "v_prediction":
target_for_loss = self.model.noise_scheduler.get_velocity(
speech_features_repeated, noise, timesteps
)
else:
raise NotImplementedError(f"Prediction type {prediction_type} not implemented")
diffusion_loss = F.mse_loss(model_output.float(), target_for_loss.float(), reduction='sum')
if latent_size > 0 and ddpm_batch_mul > 0:
diffusion_loss = diffusion_loss / latent_size / ddpm_batch_mul
else:
diffusion_loss = torch.tensor(0.0, device=diffusion_loss.device)
else:
# Dummy loss for DDP to work when there are no speech samples in a batch,
# but we are in a speech context.
diffusion_loss = sum(p.sum() for p in self.model.prediction_head.parameters()) * 0.0
diffusion_loss += sum(p.sum() for p in self.model.acoustic_connector.parameters()) * 0.0
diffusion_loss += sum(p.sum() for p in self.model.semantic_connector.parameters()) * 0.0
# --- End Diffusion Loss Calculation ---
if not return_dict:
output = (logits, speech_len) + outputs.to_tuple()[1:]
return (loss, diffusion_loss) + output
return VibeVoiceCausalLMOutputWithPast(
loss=loss,
diffusion_loss=diffusion_loss,
speech_token_num=speech_len if speech_tensors is not None else 0,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
AutoModel.register(VibeVoiceConfig, VibeVoiceModel)
AutoModelForCausalLM.register(VibeVoiceConfig, VibeVoiceForConditionalGeneration)
__all__ = [
"VibeVoiceModel",
"VibeVoicePreTrainedModel",
"VibeVoiceForConditionalGeneration",
"VibeVoiceCausalLMOutputWithPast",
"VibeVoiceGenerationOutput",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modeling_vibevoice.py",
"license": "MIT License",
"lines": 416,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modeling_vibevoice_asr.py | from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
from transformers.models.auto import AutoModel, AutoModelForCausalLM
from transformers.modeling_outputs import CausalLMOutput, BaseModelOutputWithPast
from transformers import modeling_utils
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import logging
from transformers.generation import GenerationMixin
from .modular_vibevoice_tokenizer import (
VibeVoiceTokenizerStreamingCache,
VibeVoiceTokenizerEncoderOutput
)
from .configuration_vibevoice import VibeVoiceASRConfig
from .modeling_vibevoice import (
VibeVoiceCausalLMOutputWithPast,
SpeechConnector
)
logger = logging.get_logger(__name__)
if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
# @auto_docstring
class VibeVoiceASRPreTrainedModel(PreTrainedModel):
config_class = VibeVoiceASRConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_skip_keys_device_placement = "past_key_values"
_supports_cache_class = True
_supports_flash_attn = True
_supports_flash_attn_2 = True
_supports_sdpa = True
_supports_quantized_cache = True
_supports_static_cache = True
_supports_attention_backend = True
def _init_weights(self, module):
# Use the language model's initializer_range if available
if hasattr(self.config, 'language_model_config') and hasattr(self.config.language_model_config, 'initializer_range'):
std = self.config.language_model_config.initializer_range
elif hasattr(self.config, 'decoder_config') and hasattr(self.config.decoder_config, 'initializer_range'):
std = self.config.decoder_config.initializer_range
else:
std = 0.02 # Default value
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.weight.data.fill_(1.0)
module.bias.data.zero_()
# @auto_docstring
class VibeVoiceASRModel(VibeVoiceASRPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, 'torch_dtype') and config.torch_dtype is not None:
if isinstance(config.torch_dtype, str):
dtype = getattr(torch, config.torch_dtype)
else:
dtype = config.torch_dtype
else:
dtype = torch.float32
# Initialize Qwen2 model for language modeling
lm_config = config.decoder_config
self.language_model = AutoModel.from_config(lm_config)
# Initialize speech components if needed
self.acoustic_tokenizer = AutoModel.from_config(config.acoustic_tokenizer_config).to(dtype)
self.semantic_tokenizer = AutoModel.from_config(config.semantic_tokenizer_config).to(dtype)
self.acoustic_connector = SpeechConnector(config.acoustic_vae_dim, lm_config.hidden_size).to(dtype)
self.semantic_connector = SpeechConnector(config.semantic_vae_dim, lm_config.hidden_size).to(dtype)
def get_input_embeddings(self):
if hasattr(self.language_model, 'embed_tokens'):
# If the language model has an embed_tokens attribute, return it
return self.language_model.embed_tokens
for name, attr in self.language_model.fullmap.items(): # parallel by nnscaler, the name is changed
if attr.orig_name == 'embed_tokens.weight':
return getattr(self.language_model, name)
assert False, 'should not arrive here'
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def set_speech_tokenizers(self, acoustic_tokenizer=None, semantic_tokenizer=None):
"""Set the speech tokenizers used for encoding and decoding speech."""
self.acoustic_tokenizer = acoustic_tokenizer
self.semantic_tokenizer = semantic_tokenizer
# Reset the encoder to evaluation mode
if self.acoustic_tokenizer is not None:
self.acoustic_tokenizer.eval()
if self.semantic_tokenizer is not None:
self.semantic_tokenizer.eval()
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> Union[Tuple, BaseModelOutputWithPast]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Forward through language model
outputs = self.language_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)
if not return_dict:
return outputs
return BaseModelOutputWithPast(
last_hidden_state=outputs.last_hidden_state,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class VibeVoiceASRForConditionalGeneration(VibeVoiceASRPreTrainedModel, GenerationMixin):
"""
VibeVoice model for Automatic Speech Recognition (ASR) with language modeling head for conditional generation.
This class is designed for inference and generation tasks.
"""
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
def __init__(self, config):
super().__init__(config)
self.model = VibeVoiceASRModel(config)
self.vocab_size = config.decoder_config.vocab_size
# Determine the dtype to use
if hasattr(config, 'torch_dtype') and config.torch_dtype is not None:
if isinstance(config.torch_dtype, str):
dtype = getattr(torch, config.torch_dtype)
else:
dtype = config.torch_dtype
else:
dtype = torch.float32
# Initialize lm_head with the correct dtype
self.lm_head = nn.Linear(config.decoder_config.hidden_size, self.vocab_size, bias=False).to(dtype)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def set_decoder(self, decoder):
self.model.language_model = decoder
def get_decoder(self):
return self.model.language_model
def tie_weights(self):
"""Tie the weights between the input embeddings and the output embeddings."""
if getattr(self.config.decoder_config, 'tie_word_embeddings', False):
output_embeddings = self.get_output_embeddings()
input_embeddings = self.get_input_embeddings()
if hasattr(input_embeddings, 'weight'):
output_embeddings.weight = input_embeddings.weight
else:
output_embeddings.weight = input_embeddings
def encode_speech(
self,
speech_tensors: torch.FloatTensor,
speech_masks: Optional[torch.BoolTensor] = None,
speech_semantic_tensors: Optional[torch.FloatTensor] = None,
streaming_segment_duration: float = 60.0, # seconds
):
"""
Encode speech input into features that can be used by the language model.
This method is called once before generation to process the speech input.
For long audio (>600s by default), uses streaming processing to avoid conv overflow (>2^32).
Segments are processed independently, then concatenated before final sampling.
Args:
speech_tensors: Input audio tensor [batch_size, samples]
speech_masks: Optional mask for speech features
speech_semantic_tensors: Optional pre-computed semantic tokens
streaming_segment_duration: Segment duration in seconds for streaming processing (default: 60s)
"""
if hasattr(self.config, 'torch_dtype') and self.config.torch_dtype is not None:
if isinstance(self.config.torch_dtype, str):
dtype = getattr(torch, self.config.torch_dtype)
else:
dtype = self.config.torch_dtype
else:
dtype = torch.float32
speech_tensors = speech_tensors.to(dtype)
# Ensure proper shape: (batch, samples)
if speech_tensors.ndim == 1:
speech_tensors = speech_tensors.unsqueeze(0)
batch_size, total_samples = speech_tensors.shape
sample_rate = 24000 # fix 24kHz sample rate
# Calculate segment size in samples
segment_samples = int(streaming_segment_duration * sample_rate)
# Decide whether to use streaming based on audio length
use_streaming = total_samples > segment_samples
with torch.no_grad():
if not use_streaming:
# Short audio: direct processing (original behavior)
encoder_output = self.model.acoustic_tokenizer.encode(speech_tensors.unsqueeze(1))
audio_tokens = encoder_output.sample(dist_type=self.model.acoustic_tokenizer.std_dist_type)[0]
acoustic_features = self.model.acoustic_connector(audio_tokens)
# Encode semantic features
if speech_semantic_tensors is not None:
semantic_features = self.model.semantic_connector(speech_semantic_tensors)
else:
semantic_tokens = self.model.semantic_tokenizer.encode(speech_tensors.unsqueeze(1)).mean
semantic_features = self.model.semantic_connector(semantic_tokens)
else:
# Long audio: streaming processing
# print(f"Using streaming processing for long audio: {total_samples/sample_rate:.1f}s "
# f"(segment size: {streaming_segment_duration}s)")
# Initialize caches for both tokenizers
acoustic_encoder_cache = VibeVoiceTokenizerStreamingCache()
semantic_encoder_cache = VibeVoiceTokenizerStreamingCache()
acoustic_mean_segments = []
semantic_mean_segments = []
sample_indices = torch.arange(batch_size, device=speech_tensors.device)
# Helper function from batch_asr_sft_cache.py
def _iter_segments(total_length: int, segment_length: int):
"""Iterate over audio segments with a given segment length."""
if segment_length <= 0:
raise ValueError("segment_length must be positive")
for start in range(0, total_length, segment_length):
end = min(start + segment_length, total_length)
if end > start:
yield start, end
# Process each segment for both acoustic and semantic tokenizers
segments = list(_iter_segments(total_samples, segment_samples))
num_segments = len(segments)
for seg_idx, (start, end) in enumerate(segments):
chunk = speech_tensors[:, start:end].contiguous()
if chunk.numel() == 0:
continue
# Check if this is the final segment
is_final = (seg_idx == num_segments - 1)
# Encode chunk for acoustic tokenizer (don't sample yet)
acoustic_encoder_output = self.model.acoustic_tokenizer.encode(
chunk.unsqueeze(1),
cache=acoustic_encoder_cache,
sample_indices=sample_indices,
use_cache=True,
is_final_chunk=is_final,
)
acoustic_mean_segments.append(acoustic_encoder_output.mean)
# Encode chunk for semantic tokenizer (take mean directly)
semantic_encoder_output = self.model.semantic_tokenizer.encode(
chunk.unsqueeze(1),
cache=semantic_encoder_cache,
sample_indices=sample_indices,
use_cache=True,
is_final_chunk=is_final,
)
semantic_mean_segments.append(semantic_encoder_output.mean)
# print(f"Processed {len(acoustic_mean_segments)} segments.")
# Concatenate all acoustic means and sample once
acoustic_mean_full = torch.cat(acoustic_mean_segments, dim=1).contiguous()
acoustic_encoder_output = VibeVoiceTokenizerEncoderOutput(
mean=acoustic_mean_full,
std=self.model.acoustic_tokenizer.fix_std
)
audio_tokens = acoustic_encoder_output.sample(
dist_type=self.model.acoustic_tokenizer.std_dist_type
)[0]
acoustic_features = self.model.acoustic_connector(audio_tokens)
# Concatenate all semantic means
semantic_tokens = torch.cat(semantic_mean_segments, dim=1).contiguous()
semantic_features = self.model.semantic_connector(semantic_tokens)
# Combine acoustic and semantic features
if speech_masks is not None:
combined_features = acoustic_features[speech_masks] + semantic_features[speech_masks]
else:
combined_features = acoustic_features + semantic_features
return combined_features
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
# Speech-specific arguments
speech_tensors: Optional[torch.FloatTensor] = None,
speech_masks: Optional[torch.BoolTensor] = None,
speech_semantic_tensors: Optional[torch.FloatTensor] = None,
acoustic_input_mask: Optional[torch.BoolTensor] = None,
**kwargs,
) -> Union[Tuple, CausalLMOutput]:
"""
Forward pass for the model. Handles both training and generation scenarios.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
use_cache = use_cache if use_cache is not None else getattr(self.config, 'use_cache', False)
# Process inputs
if inputs_embeds is None and input_ids is not None:
inputs_embeds = self.get_input_embeddings()(input_ids)
# If we have speech input and acoustic_input_mask, encode and insert speech features
if speech_tensors is not None and acoustic_input_mask is not None:
speech_features = self.encode_speech(
speech_tensors=speech_tensors,
speech_masks=speech_masks,
speech_semantic_tensors=speech_semantic_tensors,
)
# Clone to avoid in-place operation on leaf variable during training
inputs_embeds = inputs_embeds.clone()
inputs_embeds[acoustic_input_mask] = speech_features
# Forward through the model
outputs = self.model(
input_ids=None,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
shift_logits = shift_logits.view(-1, self.vocab_size)
shift_labels = shift_labels.view(-1)
# Enable model parallelism
shift_labels = shift_labels.to(shift_logits.device)
loss = loss_fct(shift_logits, shift_labels)
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return VibeVoiceCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
position_ids=None,
use_cache=True,
speech_tensors=None,
speech_masks=None,
speech_semantic_tensors=None,
acoustic_input_mask=None,
**kwargs,
):
"""
Prepare inputs for generation step. This method is called by generate()
for each token generation step.
Following Qwen2-VL's approach: speech inputs are only forwarded on the first pass
(when cache_position[0] == 0), and are excluded in subsequent generation steps.
"""
# If we have past key values, we only need to process the new tokens
if past_key_values is not None:
if isinstance(past_key_values, tuple):
past_length = past_key_values[0][0].shape[2]
else:
past_length = past_key_values.get_seq_length()
# Keep only the new tokens
if input_ids is not None and input_ids.shape[1] > past_length:
input_ids = input_ids[:, past_length:]
# Prepare position ids
if position_ids is None and attention_mask is not None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past_key_values is not None and input_ids is not None:
position_ids = position_ids[:, -input_ids.shape[1]:]
# Prepare cache position
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + (input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]),
device=input_ids.device if input_ids is not None else inputs_embeds.device
)
# Prepare model inputs
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
model_inputs.update(
{
"position_ids": position_ids,
"cache_position": cache_position,
"past_key_values": past_key_values,
"use_cache": use_cache,
"attention_mask": attention_mask,
}
)
# Following Qwen2-VL pattern: only include speech inputs on the first forward pass
# (when cache_position[0] == 0), exclude them in subsequent generation steps
if cache_position is not None and len(cache_position) > 0 and cache_position[0] == 0:
# First forward pass - include speech inputs if provided
model_inputs.update({
"speech_tensors": speech_tensors,
"speech_masks": speech_masks,
"speech_semantic_tensors": speech_semantic_tensors,
"acoustic_input_mask": acoustic_input_mask,
})
else:
# Subsequent generation steps - exclude speech inputs
model_inputs.update({
"speech_tensors": None,
"speech_masks": None,
"speech_semantic_tensors": None,
"acoustic_input_mask": None,
})
# Include any remaining kwargs that might be needed
model_inputs.update(kwargs)
return model_inputs
AutoModel.register(VibeVoiceASRConfig, VibeVoiceASRModel)
AutoModelForCausalLM.register(VibeVoiceASRConfig, VibeVoiceASRForConditionalGeneration)
__all__ = [
"VibeVoiceASRPreTrainedModel",
"VibeVoiceASRModel",
"VibeVoiceASRForConditionalGeneration",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modeling_vibevoice_asr.py",
"license": "MIT License",
"lines": 444,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/processor/audio_utils.py | import os
import threading
import numpy as np
from subprocess import run
from typing import List, Optional, Union, Dict, Any
COMMON_AUDIO_EXTS = [
'.mp3', '.MP3', '.Mp3', # All case variations of mp3
'.m4a',
'.mp4', '.MP4',
'.wav', '.WAV',
'.m4v',
'.aac',
'.ogg',
'.mov', '.MOV',
'.opus',
'.m4b',
'.flac',
'.wma', '.WMA',
'.rm', '.3gp', '.mpeg', '.flv', '.webm', '.mp2', '.aif', '.aiff', '.oga', '.ogv', '.mpga', '.m3u8', '.amr'
]
def load_audio_use_ffmpeg(file: str, resample: bool = False, target_sr: int = 24000):
"""
Open an audio file and read as mono waveform, optionally resampling.
Returns both the audio data and the original sample rate.
Parameters
----------
file: str
The audio file to open
resample: bool
Whether to resample the audio
target_sr: int
The target sample rate if resampling is requested
Returns
-------
A tuple containing:
- A NumPy array with the audio waveform in float32 dtype
- The original sample rate of the audio file
"""
if not resample:
# First, get the original sample rate
cmd_probe = [
"ffprobe",
"-v", "quiet",
"-show_entries", "stream=sample_rate",
"-of", "default=noprint_wrappers=1:nokey=1",
file
]
original_sr = int(run(cmd_probe, capture_output=True, check=True).stdout.decode().strip())
else:
original_sr = None
# Now load the audio
sr_to_use = target_sr if resample else original_sr
cmd = [
"ffmpeg",
"-loglevel", "error",
"-nostdin",
"-threads", "0",
"-i", file,
"-f", "s16le",
"-ac", "1",
"-acodec", "pcm_s16le",
"-ar", str(sr_to_use),
"-",
]
out = _run_ffmpeg(cmd).stdout
audio_data = np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
return audio_data, sr_to_use
def _get_ffmpeg_max_concurrency() -> int:
"""Get the maximum FFmpeg concurrency from environment variable."""
v = os.getenv("VIBEVOICE_FFMPEG_MAX_CONCURRENCY", "")
try:
n = int(v) if v.strip() else 0
except Exception:
n = 0
# 0/negative means no explicit limit.
return n
_FFMPEG_MAX_CONCURRENCY = _get_ffmpeg_max_concurrency()
_FFMPEG_SEM = threading.Semaphore(_FFMPEG_MAX_CONCURRENCY) if _FFMPEG_MAX_CONCURRENCY > 0 else None
def _run_ffmpeg(cmd: list, *, stdin_bytes: bytes = None):
"""Run ffmpeg with optional global concurrency limiting.
This is important for vLLM multi-request concurrency: spawning too many
ffmpeg processes can saturate CPU/IO and cause request failures/timeouts.
"""
if _FFMPEG_SEM is None:
return run(cmd, capture_output=True, check=True, input=stdin_bytes)
with _FFMPEG_SEM:
return run(cmd, capture_output=True, check=True, input=stdin_bytes)
def load_audio_bytes_use_ffmpeg(data: bytes, *, resample: bool = False, target_sr: int = 24000):
"""Decode audio bytes via ffmpeg stdin pipe.
Compared to writing bytes to a temp file, this avoids filesystem IO and
reduces contention under high request concurrency.
Parameters
----------
data: bytes
The audio data bytes
resample: bool
Whether to resample the audio (must be True)
target_sr: int
The target sample rate if resampling is requested
Returns
-------
A tuple containing:
- A NumPy array with the audio waveform in float32 dtype
- The sample rate
"""
if not resample:
# For stdin bytes, we don't have a cheap/robust way to probe original sr.
# Keep behavior explicit.
raise ValueError("load_audio_bytes_use_ffmpeg requires resample=True")
cmd = [
"ffmpeg",
"-loglevel", "error",
"-threads", "0",
"-i", "pipe:0",
"-f", "s16le",
"-ac", "1",
"-acodec", "pcm_s16le",
"-ar", str(target_sr),
"-",
]
out = _run_ffmpeg(cmd, stdin_bytes=data).stdout
audio_data = np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
return audio_data, target_sr
class AudioNormalizer:
"""
Audio normalization class for VibeVoice tokenizer.
This class provides audio normalization to ensure consistent input levels
for the VibeVoice tokenizer while maintaining audio quality.
"""
def __init__(self, target_dB_FS: float = -25, eps: float = 1e-6):
"""
Initialize the audio normalizer.
Args:
target_dB_FS (float): Target dB FS level for the audio. Default: -25
eps (float): Small value to avoid division by zero. Default: 1e-6
"""
self.target_dB_FS = target_dB_FS
self.eps = eps
def tailor_dB_FS(self, audio: np.ndarray) -> tuple:
"""
Adjust the audio to the target dB FS level.
Args:
audio (np.ndarray): Input audio signal
Returns:
tuple: (normalized_audio, rms, scalar)
"""
rms = np.sqrt(np.mean(audio**2))
scalar = 10 ** (self.target_dB_FS / 20) / (rms + self.eps)
normalized_audio = audio * scalar
return normalized_audio, rms, scalar
def avoid_clipping(self, audio: np.ndarray, scalar: Optional[float] = None) -> tuple:
"""
Avoid clipping by scaling down if necessary.
Args:
audio (np.ndarray): Input audio signal
scalar (float, optional): Explicit scaling factor
Returns:
tuple: (normalized_audio, scalar)
"""
if scalar is None:
max_val = np.max(np.abs(audio))
if max_val > 1.0:
scalar = max_val + self.eps
else:
scalar = 1.0
return audio / scalar, scalar
def __call__(self, audio: np.ndarray) -> np.ndarray:
"""
Normalize the audio by adjusting to target dB FS and avoiding clipping.
Args:
audio (np.ndarray): Input audio signal
Returns:
np.ndarray: Normalized audio signal
"""
# First adjust to target dB FS
audio, _, _ = self.tailor_dB_FS(audio)
# Then avoid clipping
audio, _ = self.avoid_clipping(audio)
return audio | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/processor/audio_utils.py",
"license": "MIT License",
"lines": 179,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
microsoft/VibeVoice:vibevoice/processor/vibevoice_asr_processor.py | """
Processor class for VibeVoice ASR models.
"""
import os
import json
import math
import warnings
from typing import List, Optional, Union, Dict, Any, Tuple
import numpy as np
import torch
from transformers.tokenization_utils_base import BatchEncoding
from transformers.utils import TensorType, logging
from .vibevoice_tokenizer_processor import VibeVoiceTokenizerProcessor, AudioNormalizer
try:
from .audio_utils import load_audio_use_ffmpeg
HAS_FFMPEG_UTILS = True
except ImportError:
HAS_FFMPEG_UTILS = False
warnings.warn("audio_utils not available, will fall back to soundfile for audio loading")
logger = logging.get_logger(__name__)
SYSTEM_PROMPT = "You are a helpful assistant that transcribes audio input into text output in JSON format."
class VibeVoiceASRProcessor:
"""
Processor for VibeVoice ASR (Automatic Speech Recognition) models.
This processor handles audio preprocessing and tokenization for ASR tasks,
following the exact format used in training with proper chat templates.
Args:
tokenizer: The text tokenizer for processing text
audio_processor: The audio processor for processing speech
speech_tok_compress_ratio (int): Compression ratio for speech tokenization
target_sample_rate (int): Target sample rate for audio
normalize_audio (bool): Whether to normalize audio input
"""
def __init__(
self,
tokenizer=None,
audio_processor=None,
speech_tok_compress_ratio=320,
target_sample_rate=24000,
normalize_audio=True,
**kwargs
):
self.tokenizer = tokenizer
self.audio_processor = audio_processor or VibeVoiceTokenizerProcessor(
sampling_rate=target_sample_rate,
normalize_audio=normalize_audio
)
self.speech_tok_compress_ratio = speech_tok_compress_ratio
self.target_sample_rate = target_sample_rate
self.normalize_audio = normalize_audio
if normalize_audio:
self.audio_normalizer = AudioNormalizer()
else:
self.audio_normalizer = None
# Cache special token IDs
self._cache_special_tokens()
def _cache_special_tokens(self):
"""Cache special token IDs for efficiency."""
# Add safety checks for special tokens
if hasattr(self.tokenizer, 'speech_start_id'):
self.speech_start_id = self.tokenizer.speech_start_id
else:
self.speech_start_id = self.tokenizer.convert_tokens_to_ids("<|speech_start|>")
if hasattr(self.tokenizer, 'speech_end_id'):
self.speech_end_id = self.tokenizer.speech_end_id
else:
self.speech_end_id = self.tokenizer.convert_tokens_to_ids("<|speech_end|>")
if hasattr(self.tokenizer, 'speech_pad_id'):
self.speech_pad_id = self.tokenizer.speech_pad_id
else:
self.speech_pad_id = self.tokenizer.convert_tokens_to_ids("<|speech_pad|>")
if hasattr(self.tokenizer, 'pad_id'):
self.pad_id = self.tokenizer.pad_id
elif hasattr(self.tokenizer, 'pad_token_id'):
self.pad_id = self.tokenizer.pad_token_id
else:
self.pad_id = self.tokenizer.convert_tokens_to_ids("<|endoftext|>")
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
"""
Load processor from a pretrained model path.
Args:
pretrained_model_name_or_path: Path to the pretrained model
**kwargs: Additional keyword arguments
Returns:
VibeVoiceASRProcessor: The loaded processor
"""
import json
from transformers.utils import cached_file
from vibevoice.modular.modular_vibevoice_text_tokenizer import VibeVoiceASRTextTokenizerFast
# Try to load configuration
config_path = os.path.join(pretrained_model_name_or_path, "preprocessor_config.json")
config = {}
if os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
else:
try:
config_file = cached_file(
pretrained_model_name_or_path,
"preprocessor_config.json",
**kwargs
)
with open(config_file, 'r') as f:
config = json.load(f)
except Exception as e:
logger.warning(f"Could not load preprocessor_config.json: {e}")
logger.warning("Using default configuration")
# Extract parameters
speech_tok_compress_ratio = config.get("speech_tok_compress_ratio", 3200)
target_sample_rate = config.get("target_sample_rate", 24000)
normalize_audio = config.get("normalize_audio", True)
# Load tokenizer
language_model_pretrained_name = config.get("language_model_pretrained_name", None) or kwargs.pop("language_model_pretrained_name", "Qwen/Qwen2.5-1.5B")
logger.info(f"Loading tokenizer from {language_model_pretrained_name}")
if 'qwen' in language_model_pretrained_name.lower():
tokenizer = VibeVoiceASRTextTokenizerFast.from_pretrained(
language_model_pretrained_name,
**kwargs
)
else:
raise ValueError(f"Unsupported tokenizer type for {language_model_pretrained_name}")
# Load audio processor
audio_processor = VibeVoiceTokenizerProcessor(
sampling_rate=target_sample_rate,
normalize_audio=normalize_audio,
target_dB_FS=config.get("target_dB_FS", -25),
eps=config.get("eps", 1e-6),
)
return cls(
tokenizer=tokenizer,
audio_processor=audio_processor,
speech_tok_compress_ratio=speech_tok_compress_ratio,
target_sample_rate=target_sample_rate,
normalize_audio=normalize_audio,
)
def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
"""
Save processor configuration to a directory.
Args:
save_directory: Directory to save the configuration
**kwargs: Additional keyword arguments
"""
import json
os.makedirs(save_directory, exist_ok=True)
# Save processor configuration
processor_config = {
"processor_class": "VibeVoiceASRProcessor",
"speech_tok_compress_ratio": self.speech_tok_compress_ratio,
"target_sample_rate": self.target_sample_rate,
"normalize_audio": self.normalize_audio,
"target_dB_FS": -25,
"eps": 1e-6,
}
config_path = os.path.join(save_directory, "preprocessor_config.json")
with open(config_path, 'w') as f:
json.dump(processor_config, f, indent=2)
logger.info(f"Processor configuration saved in {config_path}")
def __call__(
self,
audio: Optional[Union[str, np.ndarray, torch.Tensor, List[Union[str, np.ndarray, torch.Tensor]]]] = None,
sampling_rate: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
padding: bool = True,
max_length: Optional[int] = None,
truncation: bool = False,
add_generation_prompt: bool = True,
use_streaming: bool = True,
context_info: Optional[str] = None,
**kwargs
) -> BatchEncoding:
"""
Process audio input for ASR model.
Args:
audio: Audio input(s). Can be:
- str: Path to audio file
- np.ndarray: Audio array
- torch.Tensor: Audio tensor
- List of the above for batch processing
sampling_rate: Sampling rate of input audio
return_tensors: Output format ('pt' for PyTorch, 'np' for NumPy)
padding: Whether to pad batch inputs
max_length: Maximum sequence length
truncation: Whether to truncate long sequences
add_generation_prompt: Whether to add generation prompt for inference
use_streaming: Whether to use streaming mode (True by default, auto False if <60s)
context_info: Optional context information (e.g., hotwords, metadata) to help transcription
Returns:
BatchEncoding with:
- input_ids: Token IDs for the model
- attention_mask: Attention mask
- acoustic_input_mask: Mask indicating speech token positions
- speech_tensors: Processed speech features
- speech_masks: Valid speech masks
- vae_tok_seqlens: Length of each speech segment in tokens
"""
if audio is None:
raise ValueError("Audio input is required for ASR processing")
# Handle single vs batch input
if isinstance(audio, list):
is_batched = True
audio_list = audio
else:
is_batched = False
audio_list = [audio]
# Process each audio input
all_encodings = []
for audio_input in audio_list:
encoding = self._process_single_audio(
audio_input,
sampling_rate=sampling_rate,
add_generation_prompt=add_generation_prompt,
use_streaming=use_streaming,
context_info=context_info,
)
all_encodings.append(encoding)
# Combine into batch
batch_encoding = self._batch_encode(
all_encodings,
padding=padding,
max_length=max_length,
truncation=truncation,
return_tensors=return_tensors,
)
return batch_encoding
def _process_single_audio(
self,
audio: Union[str, np.ndarray, torch.Tensor],
sampling_rate: Optional[int] = None,
add_generation_prompt: bool = True,
use_streaming: bool = True,
context_info: Optional[str] = None,
) -> Dict[str, Any]:
"""
Process a single audio input.
Args:
audio: Single audio input
sampling_rate: Audio sampling rate
add_generation_prompt: Whether to add generation prompt
context_info: Optional context information (e.g., hotwords, metadata) to help transcription
Returns:
Dictionary with processed tokens and audio features
"""
# Process audio through audio processor
if isinstance(audio, str):
# Load from file using ffmpeg for better format support
if HAS_FFMPEG_UTILS:
try:
audio_array, file_sr = load_audio_use_ffmpeg(audio, resample=False)
except Exception as e:
# Fall back to soundfile if ffmpeg fails
warnings.warn(f"ffmpeg loading failed, falling back to soundfile: {e}")
import soundfile as sf
audio_array, file_sr = sf.read(audio)
if audio_array.ndim > 1:
audio_array = audio_array.mean(axis=1) # Convert to mono
else:
import soundfile as sf
audio_array, file_sr = sf.read(audio)
if audio_array.ndim > 1:
audio_array = audio_array.mean(axis=1) # Convert to mono
# Resample if needed
if file_sr != self.target_sample_rate:
import librosa
audio_array = librosa.resample(
audio_array,
orig_sr=file_sr,
target_sr=self.target_sample_rate
)
elif isinstance(audio, torch.Tensor):
audio_array = audio.cpu().numpy()
if audio_array.ndim > 1:
audio_array = audio_array.squeeze()
else:
audio_array = np.array(audio, dtype=np.float32)
if audio_array.ndim > 1:
audio_array = audio_array.squeeze()
# Ensure float32
audio_array = audio_array.astype(np.float32)
# Normalize if needed
if self.normalize_audio and self.audio_normalizer:
audio_array = self.audio_normalizer(audio_array)
# Calculate audio duration
audio_duration = len(audio_array) / self.target_sample_rate
# Auto-disable streaming for short audio (<60s)
if use_streaming and audio_duration < 60.0:
use_streaming = False
# Calculate token length based on streaming mode
# Non-streaming: uses ceil (encoder adds extra_padding for stride alignment)
# Streaming: uses floor (segments processed independently, no global alignment)
# if use_streaming:
# vae_tok_len = len(audio_array) // self.speech_tok_compress_ratio
# else:
vae_tok_len = math.ceil(len(audio_array) / self.speech_tok_compress_ratio)
# Build token sequence following training format
# 1. System prompt - use apply_chat_template then encode like in training
system_prompt_text = self.tokenizer.apply_chat_template(
[{"role": "system", "content": SYSTEM_PROMPT}],
tokenize=False
)
system_tokens = self.tokenizer.encode(system_prompt_text)
# 2. User input with speech tokens
# Build speech placeholder string
sp_start_token = self.tokenizer.convert_ids_to_tokens(self.speech_start_id)
sp_pad_token = self.tokenizer.convert_ids_to_tokens(self.speech_pad_id)
sp_end_token = self.tokenizer.convert_ids_to_tokens(self.speech_end_id)
# User suffix with audio duration info
show_keys = ['Start time', 'End time', 'Speaker ID', 'Content']
if context_info and context_info.strip():
user_suffix = f"This is a {audio_duration:.2f} seconds audio, with extra info: {context_info.strip()}\n\nPlease transcribe it with these keys: " + ", ".join(show_keys)
else:
user_suffix = f"This is a {audio_duration:.2f} seconds audio, please transcribe it with these keys: " + ", ".join(show_keys)
user_input_string = ''.join(
[sp_start_token] + [sp_pad_token] * vae_tok_len + [sp_end_token]
) + '\n' + user_suffix
user_tokens = self.tokenizer.apply_chat_template(
[{"role": "user", "content": user_input_string}],
tokenize=True
)
# Combine tokens
full_tokens = system_tokens + user_tokens
# Create acoustic input mask
acoustic_input_mask = [1 if token == self.speech_pad_id else 0 for token in full_tokens]
return {
"input_ids": full_tokens,
"acoustic_input_mask": acoustic_input_mask,
"speech": audio_array,
"vae_tok_len": vae_tok_len,
}
def _batch_encode(
self,
encodings: List[Dict[str, Any]],
padding: bool = True,
max_length: Optional[int] = None,
truncation: bool = False,
return_tensors: Optional[str] = None,
) -> BatchEncoding:
"""
Combine multiple encodings into a batch.
Args:
encodings: List of encoded samples
padding: Whether to pad sequences
max_length: Maximum sequence length
truncation: Whether to truncate
return_tensors: Output format
Returns:
BatchEncoding with batched data
"""
# Extract components
input_ids_list = [enc["input_ids"] for enc in encodings]
acoustic_masks_list = [enc["acoustic_input_mask"] for enc in encodings]
speech_list = [enc["speech"] for enc in encodings]
vae_tok_lens = [enc["vae_tok_len"] for enc in encodings]
# Determine max length for padding
if padding:
if max_length is not None:
target_length = max_length
else:
target_length = max(len(ids) for ids in input_ids_list)
# Pad sequences
padded_input_ids = []
padded_acoustic_masks = []
attention_masks = []
for input_ids, acoustic_mask in zip(input_ids_list, acoustic_masks_list):
# Truncate if needed
if truncation and len(input_ids) > target_length:
input_ids = input_ids[:target_length]
acoustic_mask = acoustic_mask[:target_length]
# Pad sequences to left (for autoregressive generation)
padding_length = target_length - len(input_ids)
padded_ids = [self.pad_id] * padding_length + input_ids
padded_acoustic = [0] * padding_length + acoustic_mask
attention_mask = [0] * padding_length + [1] * len(input_ids)
padded_input_ids.append(padded_ids)
padded_acoustic_masks.append(padded_acoustic)
attention_masks.append(attention_mask)
input_ids_list = padded_input_ids
acoustic_masks_list = padded_acoustic_masks
else:
attention_masks = [[1] * len(ids) for ids in input_ids_list]
# Process speech tensors - raw audio is 1D, so we keep it as is
max_speech_length = max(len(s) for s in speech_list)
padded_speeches = np.zeros((len(speech_list), max_speech_length), dtype=np.float32)
speech_masks = np.zeros((len(speech_list), max(vae_tok_lens)), dtype=bool)
for i, (speech, vae_len) in enumerate(zip(speech_list, vae_tok_lens)):
padded_speeches[i, :len(speech)] = speech
speech_masks[i, :vae_len] = True
# Create batch encoding
batch_encoding = BatchEncoding()
if return_tensors == "pt":
batch_encoding["input_ids"] = torch.tensor(input_ids_list, dtype=torch.long)
batch_encoding["attention_mask"] = torch.tensor(attention_masks, dtype=torch.long)
batch_encoding["acoustic_input_mask"] = torch.tensor(acoustic_masks_list, dtype=torch.bool)
batch_encoding["speech_tensors"] = torch.tensor(padded_speeches, dtype=torch.float32)
batch_encoding["speech_masks"] = torch.tensor(speech_masks, dtype=torch.bool)
# Note: vae_tok_seqlens and speech_type are not included as they are not model inputs
else:
batch_encoding["input_ids"] = input_ids_list if len(input_ids_list) > 1 else input_ids_list[0]
batch_encoding["attention_mask"] = attention_masks if len(attention_masks) > 1 else attention_masks[0]
batch_encoding["acoustic_input_mask"] = acoustic_masks_list if len(acoustic_masks_list) > 1 else acoustic_masks_list[0]
batch_encoding["speech_tensors"] = padded_speeches if len(padded_speeches) > 1 else padded_speeches[0]
batch_encoding["speech_masks"] = speech_masks if len(speech_masks) > 1 else speech_masks[0]
return batch_encoding
def batch_decode(self, *args, **kwargs):
"""
Decode batch of token IDs to text.
Forwards to tokenizer's batch_decode method.
"""
return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs):
"""
Decode token IDs to text.
Forwards to tokenizer's decode method.
"""
return self.tokenizer.decode(*args, **kwargs)
def post_process_transcription(self, text: str) -> List[Dict[str, Any]]:
"""
Post-process the generated transcription text to extract structured data.
Args:
text: Generated text from the model
Returns:
List of dictionaries with transcription segments
"""
try:
# Try to parse as JSON
if "```json" in text:
# Extract JSON from markdown code block
json_start = text.find("```json") + 7
json_end = text.find("```", json_start)
json_str = text[json_start:json_end].strip()
else:
# Try to find JSON array or object
json_start = text.find("[")
if json_start == -1:
json_start = text.find("{")
if json_start != -1:
# Find matching closing bracket
bracket_count = 0
json_end = json_start
for i in range(json_start, len(text)):
if text[i] in "[{":
bracket_count += 1
elif text[i] in "]}":
bracket_count -= 1
if bracket_count == 0:
json_end = i + 1
break
json_str = text[json_start:json_end]
else:
json_str = text
# Parse JSON
result = json.loads(json_str)
# Ensure it's a list
if isinstance(result, dict):
result = [result]
# Validate and clean up the result
cleaned_result = []
for item in result:
if isinstance(item, dict):
cleaned_item = {}
# Map keys to expected format
key_mapping = {
"Start time": "start_time",
"Start": "start_time",
"End time": "end_time",
"End": "end_time",
"Speaker ID": "speaker_id",
"Speaker": "speaker_id",
"Content": "text",
}
for key, mapped_key in key_mapping.items():
if key in item:
cleaned_item[mapped_key] = item[key]
if cleaned_item:
cleaned_result.append(cleaned_item)
return cleaned_result
except json.JSONDecodeError as e:
logger.warning(f"Failed to parse JSON from transcription: {e}")
logger.debug(f"Raw text: {text}")
return []
except Exception as e:
logger.warning(f"Error post-processing transcription: {e}")
return []
@property
def model_input_names(self):
"""Return the list of inputs accepted by the model."""
return ["input_ids", "attention_mask", "acoustic_input_mask", "speech_tensors", "speech_masks"]
__all__ = ["VibeVoiceASRProcessor"]
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/processor/vibevoice_asr_processor.py",
"license": "MIT License",
"lines": 488,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:demo/realtime_model_inference_from_file.py | import argparse
import os
import re
import traceback
from typing import List, Tuple, Union, Dict, Any
import time
import torch
import copy
import glob
from vibevoice.modular.modeling_vibevoice_streaming_inference import VibeVoiceStreamingForConditionalGenerationInference
from vibevoice.processor.vibevoice_streaming_processor import VibeVoiceStreamingProcessor
from transformers.utils import logging
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
class VoiceMapper:
"""Maps speaker names to voice file paths"""
def __init__(self):
self.setup_voice_presets()
# for k, v in self.voice_presets.items():
# print(f"{k}: {v}")
def setup_voice_presets(self):
"""Setup voice presets by scanning the voices directory."""
voices_dir = os.path.join(os.path.dirname(__file__), "voices/streaming_model")
# Check if voices directory exists
if not os.path.exists(voices_dir):
print(f"Warning: Voices directory not found at {voices_dir}")
self.voice_presets = {}
self.available_voices = {}
return
# Scan for all VOICE files in the voices directory
self.voice_presets = {}
# Get all .pt files in the voices directory
pt_files = glob.glob(os.path.join(voices_dir, "**", "*.pt"), recursive=True)
# Create dictionary with filename (without extension) as key
for pt_file in pt_files:
# key: filename without extension
name = os.path.splitext(os.path.basename(pt_file))[0].lower()
full_path = os.path.abspath(pt_file)
self.voice_presets[name] = full_path
# Sort the voice presets alphabetically by name for better UI
self.voice_presets = dict(sorted(self.voice_presets.items()))
# Filter out voices that don't exist (this is now redundant but kept for safety)
self.available_voices = {
name: path for name, path in self.voice_presets.items()
if os.path.exists(path)
}
print(f"Found {len(self.available_voices)} voice files in {voices_dir}")
print(f"Available voices: {', '.join(self.available_voices.keys())}")
def get_voice_path(self, speaker_name: str) -> str:
"""Get voice file path for a given speaker name"""
# First try exact match
speaker_name = speaker_name.lower()
if speaker_name in self.voice_presets:
return self.voice_presets[speaker_name]
# Try partial matching (case insensitive)
matched_path = None
for preset_name, path in self.voice_presets.items():
if preset_name.lower() in speaker_name or speaker_name in preset_name.lower():
if matched_path is not None:
raise ValueError(f"Multiple voice presets match the speaker name '{speaker_name}', please make the speaker_name more specific.")
matched_path = path
if matched_path is not None:
return matched_path
# Default to first voice if no match found
default_voice = list(self.voice_presets.values())[0]
print(f"Warning: No voice preset found for '{speaker_name}', using default voice: {default_voice}")
return default_voice
def parse_args():
parser = argparse.ArgumentParser(description="VibeVoiceStreaming Processor TXT Input Test")
parser.add_argument(
"--model_path",
type=str,
default="microsoft/VibeVoice-Realtime-0.5B",
help="Path to the HuggingFace model directory",
)
parser.add_argument(
"--txt_path",
type=str,
default="demo/text_examples/1p_vibevoice.txt",
help="Path to the txt file containing the script",
)
parser.add_argument(
"--speaker_name",
type=str,
default="Wayne",
help="Single speaker name (e.g., --speaker_name Wayne)",
)
parser.add_argument(
"--output_dir",
type=str,
default="./outputs",
help="Directory to save output audio files",
)
parser.add_argument(
"--device",
type=str,
default=("cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")),
help="Device for inference: cuda | mps | cpu",
)
parser.add_argument(
"--cfg_scale",
type=float,
default=1.5,
help="CFG (Classifier-Free Guidance) scale for generation (default: 1.5)",
)
return parser.parse_args()
def main():
args = parse_args()
# Normalize potential 'mpx' typo to 'mps'
if args.device.lower() == "mpx":
print("Note: device 'mpx' detected, treating it as 'mps'.")
args.device = "mps"
# Validate mps availability if requested
if args.device == "mps" and not torch.backends.mps.is_available():
print("Warning: MPS not available. Falling back to CPU.")
args.device = "cpu"
print(f"Using device: {args.device}")
# Initialize voice mapper
voice_mapper = VoiceMapper()
# Check if txt file exists
if not os.path.exists(args.txt_path):
print(f"Error: txt file not found: {args.txt_path}")
return
# Read and parse txt file
print(f"Reading script from: {args.txt_path}")
with open(args.txt_path, 'r', encoding='utf-8') as f:
scripts = f.read().strip()
if not scripts:
print("Error: No valid scripts found in the txt file")
return
full_script = scripts.replace("’", "'").replace('“', '"').replace('”', '"')
print(f"Loading processor & model from {args.model_path}")
processor = VibeVoiceStreamingProcessor.from_pretrained(args.model_path)
# Decide dtype & attention implementation
if args.device == "mps":
load_dtype = torch.float32 # MPS requires float32
attn_impl_primary = "sdpa" # flash_attention_2 not supported on MPS
elif args.device == "cuda":
load_dtype = torch.bfloat16
attn_impl_primary = "flash_attention_2"
else: # cpu
load_dtype = torch.float32
attn_impl_primary = "sdpa"
print(f"Using device: {args.device}, torch_dtype: {load_dtype}, attn_implementation: {attn_impl_primary}")
# Load model with device-specific logic
try:
if args.device == "mps":
model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
args.model_path,
torch_dtype=load_dtype,
attn_implementation=attn_impl_primary,
device_map=None, # load then move
)
model.to("mps")
elif args.device == "cuda":
model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
args.model_path,
torch_dtype=load_dtype,
device_map="cuda",
attn_implementation=attn_impl_primary,
)
else: # cpu
model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
args.model_path,
torch_dtype=load_dtype,
device_map="cpu",
attn_implementation=attn_impl_primary,
)
except Exception as e:
if attn_impl_primary == 'flash_attention_2':
print(f"[ERROR] : {type(e).__name__}: {e}")
print(traceback.format_exc())
print("Error loading the model. Trying to use SDPA. However, note that only flash_attention_2 has been fully tested, and using SDPA may result in lower audio quality.")
model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
args.model_path,
torch_dtype=load_dtype,
device_map=(args.device if args.device in ("cuda", "cpu") else None),
attn_implementation='sdpa'
)
if args.device == "mps":
model.to("mps")
else:
raise e
model.eval()
model.set_ddpm_inference_steps(num_steps=5)
if hasattr(model.model, 'language_model'):
print(f"Language model attention: {model.model.language_model.config._attn_implementation}")
target_device = args.device if args.device != "cpu" else "cpu"
voice_sample = voice_mapper.get_voice_path(args.speaker_name)
print(f"Using voice preset for {args.speaker_name}: {voice_sample}")
all_prefilled_outputs = torch.load(voice_sample, map_location=target_device, weights_only=False)
# Prepare inputs for the model
inputs = processor.process_input_with_cached_prompt(
text=full_script,
cached_prompt=all_prefilled_outputs,
padding=True,
return_tensors="pt",
return_attention_mask=True,
)
# Move tensors to target device
for k, v in inputs.items():
if torch.is_tensor(v):
inputs[k] = v.to(target_device)
print(f"Starting generation with cfg_scale: {args.cfg_scale}")
# Generate audio
start_time = time.time()
outputs = model.generate(
**inputs,
max_new_tokens=None,
cfg_scale=args.cfg_scale,
tokenizer=processor.tokenizer,
generation_config={'do_sample': False},
verbose=True,
all_prefilled_outputs=copy.deepcopy(all_prefilled_outputs) if all_prefilled_outputs is not None else None,
)
generation_time = time.time() - start_time
print(f"Generation time: {generation_time:.2f} seconds")
# Calculate audio duration and additional metrics
if outputs.speech_outputs and outputs.speech_outputs[0] is not None:
# Assuming 24kHz sample rate (common for speech synthesis)
sample_rate = 24000
audio_samples = outputs.speech_outputs[0].shape[-1] if len(outputs.speech_outputs[0].shape) > 0 else len(outputs.speech_outputs[0])
audio_duration = audio_samples / sample_rate
rtf = generation_time / audio_duration if audio_duration > 0 else float('inf')
print(f"Generated audio duration: {audio_duration:.2f} seconds")
print(f"RTF (Real Time Factor): {rtf:.2f}x")
else:
print("No audio output generated")
# Calculate token metrics
input_tokens = inputs['tts_text_ids'].shape[1] # Number of input tokens
output_tokens = outputs.sequences.shape[1] # Total tokens (input + generated)
generated_tokens = output_tokens - input_tokens - all_prefilled_outputs['tts_lm']['last_hidden_state'].size(1)
print(f"Prefilling text tokens: {input_tokens}")
print(f"Generated speech tokens: {generated_tokens}")
print(f"Total tokens: {output_tokens}")
# Save output (processor handles device internally)
txt_filename = os.path.splitext(os.path.basename(args.txt_path))[0]
output_path = os.path.join(args.output_dir, f"{txt_filename}_generated.wav")
os.makedirs(args.output_dir, exist_ok=True)
processor.save_audio(
outputs.speech_outputs[0], # First (and only) batch item
output_path=output_path,
)
print(f"Saved output to {output_path}")
# Print summary
print("\n" + "="*50)
print("GENERATION SUMMARY")
print("="*50)
print(f"Input file: {args.txt_path}")
print(f"Output file: {output_path}")
print(f"Speaker names: {args.speaker_name}")
print(f"Prefilling text tokens: {input_tokens}")
print(f"Generated speech tokens: {generated_tokens}")
print(f"Total tokens: {output_tokens}")
print(f"Generation time: {generation_time:.2f} seconds")
print(f"Audio duration: {audio_duration:.2f} seconds")
print(f"RTF (Real Time Factor): {rtf:.2f}x")
print("="*50)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "demo/realtime_model_inference_from_file.py",
"license": "MIT License",
"lines": 260,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:demo/vibevoice_realtime_demo.py | import argparse, os, uvicorn
def main():
p = argparse.ArgumentParser()
p.add_argument("--port", type=int, default=3000)
p.add_argument("--model_path", type=str, default="microsoft/VibeVoice-Realtime-0.5B")
p.add_argument("--device", type=str, default="cuda", choices=["cpu", "cuda", "mpx", "mps"])
p.add_argument("--reload", action="store_true", help="Reload the model or not")
args = p.parse_args()
os.environ["MODEL_PATH"] = args.model_path
os.environ["MODEL_DEVICE"] = args.device
uvicorn.run("web.app:app", host="0.0.0.0", port=args.port, reload=args.reload)
if __name__ == "__main__":
main()
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "demo/vibevoice_realtime_demo.py",
"license": "MIT License",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/VibeVoice:demo/web/app.py | import datetime
import builtins
import asyncio
import json
import os
import threading
import traceback
from pathlib import Path
from queue import Empty, Queue
from typing import Any, Callable, Dict, Iterator, Optional, Tuple, cast
import numpy as np
import torch
from fastapi import FastAPI, WebSocket
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from starlette.websockets import WebSocketDisconnect, WebSocketState
from vibevoice.modular.modeling_vibevoice_streaming_inference import (
VibeVoiceStreamingForConditionalGenerationInference,
)
from vibevoice.processor.vibevoice_streaming_processor import (
VibeVoiceStreamingProcessor,
)
from vibevoice.modular.streamer import AudioStreamer
import copy
BASE = Path(__file__).parent
SAMPLE_RATE = 24_000
def get_timestamp():
timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc
).astimezone(
datetime.timezone(datetime.timedelta(hours=8))
).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
return timestamp
class StreamingTTSService:
def __init__(
self,
model_path: str,
device: str = "cuda",
inference_steps: int = 5,
) -> None:
# Keep model_path as string for HuggingFace repo IDs (Path() converts / to \ on Windows)
self.model_path = model_path
self.inference_steps = inference_steps
self.sample_rate = SAMPLE_RATE
self.processor: Optional[VibeVoiceStreamingProcessor] = None
self.model: Optional[VibeVoiceStreamingForConditionalGenerationInference] = None
self.voice_presets: Dict[str, Path] = {}
self.default_voice_key: Optional[str] = None
self._voice_cache: Dict[str, Tuple[object, Path, str]] = {}
if device == "mpx":
print("Note: device 'mpx' detected, treating it as 'mps'.")
device = "mps"
if device == "mps" and not torch.backends.mps.is_available():
print("Warning: MPS not available. Falling back to CPU.")
device = "cpu"
self.device = device
self._torch_device = torch.device(device)
def load(self) -> None:
print(f"[startup] Loading processor from {self.model_path}")
self.processor = VibeVoiceStreamingProcessor.from_pretrained(self.model_path)
# Decide dtype & attention
if self.device == "mps":
load_dtype = torch.float32
device_map = None
attn_impl_primary = "sdpa"
elif self.device == "cuda":
load_dtype = torch.bfloat16
device_map = 'cuda'
attn_impl_primary = "flash_attention_2"
else:
load_dtype = torch.float32
device_map = 'cpu'
attn_impl_primary = "sdpa"
print(f"Using device: {device_map}, torch_dtype: {load_dtype}, attn_implementation: {attn_impl_primary}")
# Load model
try:
self.model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
self.model_path,
torch_dtype=load_dtype,
device_map=device_map,
attn_implementation=attn_impl_primary,
)
if self.device == "mps":
self.model.to("mps")
except Exception as e:
if attn_impl_primary == 'flash_attention_2':
print("Error loading the model. Trying to use SDPA. However, note that only flash_attention_2 has been fully tested, and using SDPA may result in lower audio quality.")
self.model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
self.model_path,
torch_dtype=load_dtype,
device_map=self.device,
attn_implementation='sdpa',
)
print("Load model with SDPA successfully ")
else:
raise e
self.model.eval()
self.model.model.noise_scheduler = self.model.model.noise_scheduler.from_config(
self.model.model.noise_scheduler.config,
algorithm_type="sde-dpmsolver++",
beta_schedule="squaredcos_cap_v2",
)
self.model.set_ddpm_inference_steps(num_steps=self.inference_steps)
self.voice_presets = self._load_voice_presets()
preset_name = os.environ.get("VOICE_PRESET")
self.default_voice_key = self._determine_voice_key(preset_name)
self._ensure_voice_cached(self.default_voice_key)
def _load_voice_presets(self) -> Dict[str, Path]:
voices_dir = BASE.parent / "voices" / "streaming_model"
if not voices_dir.exists():
raise RuntimeError(f"Voices directory not found: {voices_dir}")
presets: Dict[str, Path] = {}
for pt_path in voices_dir.rglob("*.pt"):
presets[pt_path.stem] = pt_path
if not presets:
raise RuntimeError(f"No voice preset (.pt) files found in {voices_dir}")
print(f"[startup] Found {len(presets)} voice presets")
return dict(sorted(presets.items()))
def _determine_voice_key(self, name: Optional[str]) -> str:
if name and name in self.voice_presets:
return name
default_key = "en-Carter_man"
if default_key in self.voice_presets:
return default_key
first_key = next(iter(self.voice_presets))
print(f"[startup] Using fallback voice preset: {first_key}")
return first_key
def _ensure_voice_cached(self, key: str) -> Tuple[object, Path, str]:
if key not in self.voice_presets:
raise RuntimeError(f"Voice preset {key!r} not found")
if key not in self._voice_cache:
preset_path = self.voice_presets[key]
print(f"[startup] Loading voice preset {key} from {preset_path}")
print(f"[startup] Loading prefilled prompt from {preset_path}")
prefilled_outputs = torch.load(
preset_path,
map_location=self._torch_device,
weights_only=False,
)
self._voice_cache[key] = prefilled_outputs
return self._voice_cache[key]
def _get_voice_resources(self, requested_key: Optional[str]) -> Tuple[str, object, Path, str]:
key = requested_key if requested_key and requested_key in self.voice_presets else self.default_voice_key
if key is None:
key = next(iter(self.voice_presets))
self.default_voice_key = key
prefilled_outputs = self._ensure_voice_cached(key)
return key, prefilled_outputs
def _prepare_inputs(self, text: str, prefilled_outputs: object):
if not self.processor or not self.model:
raise RuntimeError("StreamingTTSService not initialized")
processor_kwargs = {
"text": text.strip(),
"cached_prompt": prefilled_outputs,
"padding": True,
"return_tensors": "pt",
"return_attention_mask": True,
}
processed = self.processor.process_input_with_cached_prompt(**processor_kwargs)
prepared = {
key: value.to(self._torch_device) if hasattr(value, "to") else value
for key, value in processed.items()
}
return prepared
def _run_generation(
self,
inputs,
audio_streamer: AudioStreamer,
errors,
cfg_scale: float,
do_sample: bool,
temperature: float,
top_p: float,
refresh_negative: bool,
prefilled_outputs,
stop_event: threading.Event,
) -> None:
try:
self.model.generate(
**inputs,
max_new_tokens=None,
cfg_scale=cfg_scale,
tokenizer=self.processor.tokenizer,
generation_config={
"do_sample": do_sample,
"temperature": temperature if do_sample else 1.0,
"top_p": top_p if do_sample else 1.0,
},
audio_streamer=audio_streamer,
stop_check_fn=stop_event.is_set,
verbose=False,
refresh_negative=refresh_negative,
all_prefilled_outputs=copy.deepcopy(prefilled_outputs),
)
except Exception as exc: # pragma: no cover - diagnostic logging
errors.append(exc)
traceback.print_exc()
audio_streamer.end()
def stream(
self,
text: str,
cfg_scale: float = 1.5,
do_sample: bool = False,
temperature: float = 0.9,
top_p: float = 0.9,
refresh_negative: bool = True,
inference_steps: Optional[int] = None,
voice_key: Optional[str] = None,
log_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None,
stop_event: Optional[threading.Event] = None,
) -> Iterator[np.ndarray]:
if not text.strip():
return
text = text.replace("’", "'")
selected_voice, prefilled_outputs = self._get_voice_resources(voice_key)
def emit(event: str, **payload: Any) -> None:
if log_callback:
try:
log_callback(event, **payload)
except Exception as exc:
print(f"[log_callback] Error while emitting {event}: {exc}")
steps_to_use = self.inference_steps
if inference_steps is not None:
try:
parsed_steps = int(inference_steps)
if parsed_steps > 0:
steps_to_use = parsed_steps
except (TypeError, ValueError):
pass
if self.model:
self.model.set_ddpm_inference_steps(num_steps=steps_to_use)
self.inference_steps = steps_to_use
inputs = self._prepare_inputs(text, prefilled_outputs)
audio_streamer = AudioStreamer(batch_size=1, stop_signal=None, timeout=None)
errors: list = []
stop_signal = stop_event or threading.Event()
thread = threading.Thread(
target=self._run_generation,
kwargs={
"inputs": inputs,
"audio_streamer": audio_streamer,
"errors": errors,
"cfg_scale": cfg_scale,
"do_sample": do_sample,
"temperature": temperature,
"top_p": top_p,
"refresh_negative": refresh_negative,
"prefilled_outputs": prefilled_outputs,
"stop_event": stop_signal,
},
daemon=True,
)
thread.start()
generated_samples = 0
try:
stream = audio_streamer.get_stream(0)
for audio_chunk in stream:
if torch.is_tensor(audio_chunk):
audio_chunk = audio_chunk.detach().cpu().to(torch.float32).numpy()
else:
audio_chunk = np.asarray(audio_chunk, dtype=np.float32)
if audio_chunk.ndim > 1:
audio_chunk = audio_chunk.reshape(-1)
peak = np.max(np.abs(audio_chunk)) if audio_chunk.size else 0.0
if peak > 1.0:
audio_chunk = audio_chunk / peak
generated_samples += int(audio_chunk.size)
emit(
"model_progress",
generated_sec=generated_samples / self.sample_rate,
chunk_sec=audio_chunk.size / self.sample_rate,
)
chunk_to_yield = audio_chunk.astype(np.float32, copy=False)
yield chunk_to_yield
finally:
stop_signal.set()
audio_streamer.end()
thread.join()
if errors:
emit("generation_error", message=str(errors[0]))
raise errors[0]
def chunk_to_pcm16(self, chunk: np.ndarray) -> bytes:
chunk = np.clip(chunk, -1.0, 1.0)
pcm = (chunk * 32767.0).astype(np.int16)
return pcm.tobytes()
app = FastAPI()
@app.on_event("startup")
async def _startup() -> None:
model_path = os.environ.get("MODEL_PATH")
if not model_path:
raise RuntimeError("MODEL_PATH not set in environment")
device = os.environ.get("MODEL_DEVICE", "cuda")
service = StreamingTTSService(
model_path=model_path,
device=device
)
service.load()
app.state.tts_service = service
app.state.model_path = model_path
app.state.device = device
app.state.websocket_lock = asyncio.Lock()
print("[startup] Model ready.")
def streaming_tts(text: str, **kwargs) -> Iterator[np.ndarray]:
service: StreamingTTSService = app.state.tts_service
yield from service.stream(text, **kwargs)
@app.websocket("/stream")
async def websocket_stream(ws: WebSocket) -> None:
await ws.accept()
text = ws.query_params.get("text", "")
print(f"Client connected, text={text!r}")
cfg_param = ws.query_params.get("cfg")
steps_param = ws.query_params.get("steps")
voice_param = ws.query_params.get("voice")
try:
cfg_scale = float(cfg_param) if cfg_param is not None else 1.5
except ValueError:
cfg_scale = 1.5
if cfg_scale <= 0:
cfg_scale = 1.5
try:
inference_steps = int(steps_param) if steps_param is not None else None
if inference_steps is not None and inference_steps <= 0:
inference_steps = None
except ValueError:
inference_steps = None
service: StreamingTTSService = app.state.tts_service
lock: asyncio.Lock = app.state.websocket_lock
if lock.locked():
busy_message = {
"type": "log",
"event": "backend_busy",
"data": {"message": "Please wait for the other requests to complete."},
"timestamp": get_timestamp(),
}
print("Please wait for the other requests to complete.")
try:
await ws.send_text(json.dumps(busy_message))
except Exception:
pass
await ws.close(code=1013, reason="Service busy")
return
acquired = False
try:
await lock.acquire()
acquired = True
log_queue: "Queue[Dict[str, Any]]" = Queue()
def enqueue_log(event: str, **data: Any) -> None:
log_queue.put({"event": event, "data": data})
async def flush_logs() -> None:
while True:
try:
entry = log_queue.get_nowait()
except Empty:
break
message = {
"type": "log",
"event": entry.get("event"),
"data": entry.get("data", {}),
"timestamp": get_timestamp(),
}
try:
await ws.send_text(json.dumps(message))
except Exception:
break
enqueue_log(
"backend_request_received",
text_length=len(text or ""),
cfg_scale=cfg_scale,
inference_steps=inference_steps,
voice=voice_param,
)
stop_signal = threading.Event()
iterator = streaming_tts(
text,
cfg_scale=cfg_scale,
inference_steps=inference_steps,
voice_key=voice_param,
log_callback=enqueue_log,
stop_event=stop_signal,
)
sentinel = object()
first_ws_send_logged = False
await flush_logs()
try:
while ws.client_state == WebSocketState.CONNECTED:
await flush_logs()
chunk = await asyncio.to_thread(next, iterator, sentinel)
if chunk is sentinel:
break
chunk = cast(np.ndarray, chunk)
payload = service.chunk_to_pcm16(chunk)
await ws.send_bytes(payload)
if not first_ws_send_logged:
first_ws_send_logged = True
enqueue_log("backend_first_chunk_sent")
await flush_logs()
except WebSocketDisconnect:
print("Client disconnected (WebSocketDisconnect)")
enqueue_log("client_disconnected")
stop_signal.set()
except Exception as e:
print(f"Error in websocket stream: {e}")
traceback.print_exc()
enqueue_log("backend_error", message=str(e))
stop_signal.set()
finally:
stop_signal.set()
enqueue_log("backend_stream_complete")
await flush_logs()
try:
iterator_close = getattr(iterator, "close", None)
if callable(iterator_close):
iterator_close()
except Exception:
pass
# clear the log queue
while not log_queue.empty():
try:
log_queue.get_nowait()
except Empty:
break
try:
if ws.client_state == WebSocketState.CONNECTED:
await ws.close()
except Exception as e:
print(f"Error closing websocket: {e}")
print("WS handler exit")
finally:
if acquired:
lock.release()
@app.get("/")
def index():
return FileResponse(BASE / "index.html")
@app.get("/config")
def get_config():
service: StreamingTTSService = app.state.tts_service
voices = sorted(service.voice_presets.keys())
return {
"voices": voices,
"default_voice": service.default_voice_key,
}
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "demo/web/app.py",
"license": "MIT License",
"lines": 441,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/configuration_vibevoice.py | """ VibeVoice_AcousticTokenizer model configuration"""
from typing import Dict, List, Optional, Tuple
import torch
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
logger = logging.get_logger(__name__)
def _convert_dtype_to_string(config_dict: dict) -> dict:
"""
Convert torch.dtype objects to their string representation for JSON serialization.
This fixes the "Object of type dtype is not JSON serializable" error that occurs
when transformers tries to log/serialize the config with torch_dtype as a torch.dtype object.
See: https://github.com/microsoft/VibeVoice/issues/199
"""
if "torch_dtype" in config_dict and config_dict["torch_dtype"] is not None:
dtype = config_dict["torch_dtype"]
if isinstance(dtype, torch.dtype):
# Convert torch.dtype to string (e.g., torch.bfloat16 -> "bfloat16")
config_dict["torch_dtype"] = str(dtype).replace("torch.", "")
return config_dict
class VibeVoiceAcousticTokenizerConfig(PretrainedConfig):
model_type = "vibevoice_acoustic_tokenizer"
def __init__(
self,
channels: int = 1,
corpus_normalize: float = 0.0,
causal: bool = True,
vae_dim: int = 64,
fix_std: float = 0.5,
std_dist_type: str = 'gaussian',
# common
mixer_layer: str = 'depthwise_conv',
conv_norm: str = 'none',
pad_mode: str = 'constant',
disable_last_norm: bool = True,
layernorm: str = 'RMSNorm',
layernorm_eps: float = 1e-5,
layernorm_elementwise_affine: bool = True,
conv_bias: bool = True,
layer_scale_init_value: float = 1e-6,
weight_init_value: float = 1e-2,
# encoder specific
encoder_n_filters: int = 32,
encoder_ratios: Optional[List[int]] = [8,5,5,4,2,2],
encoder_depths: str = "3-3-3-3-3-3-8",
# decoder specific
decoder_n_filters: int = 32,
decoder_ratios: Optional[List[int]] = None, # if None, same as encoder
decoder_depths: Optional[str] = None,
**kwargs
):
super().__init__(**kwargs)
self.channels = channels
self.corpus_normalize = corpus_normalize
self.causal = causal
self.vae_dim = vae_dim
self.fix_std = fix_std
self.std_dist_type = std_dist_type
# common parameters
self.conv_norm = conv_norm
self.pad_mode = pad_mode
self.layernorm_eps = layernorm_eps
self.disable_last_norm = disable_last_norm
self.layernorm = layernorm
self.layernorm_elementwise_affine = layernorm_elementwise_affine
self.conv_bias = conv_bias
self.layer_scale_init_value = layer_scale_init_value
self.weight_init_value = weight_init_value
self.mixer_layer = mixer_layer
# encoder specific parameters
self.encoder_n_filters = encoder_n_filters
self.encoder_ratios = encoder_ratios
self.encoder_depths = encoder_depths
# decoder specific parameters
self.decoder_ratios = decoder_ratios if decoder_ratios is not None else encoder_ratios
self.decoder_n_filters = decoder_n_filters
self.decoder_depths = decoder_depths
class VibeVoiceSemanticTokenizerConfig(PretrainedConfig):
model_type = "vibevoice_semantic_tokenizer"
def __init__(
self,
channels: int = 1,
corpus_normalize: float = 0.0,
causal: bool = True,
vae_dim: int = 64,
fix_std: float = 0,
std_dist_type: str = 'none',
# common
mixer_layer: str = 'depthwise_conv',
conv_norm: str = 'none',
pad_mode: str = 'constant',
disable_last_norm: bool = True,
layernorm: str = 'RMSNorm',
layernorm_eps: float = 1e-5,
layernorm_elementwise_affine: bool = True,
conv_bias: bool = True,
layer_scale_init_value: float = 1e-6,
weight_init_value: float = 1e-2,
# encoder specific
encoder_n_filters: int = 32,
encoder_ratios: Optional[List[int]] = [8,5,5,4,2,2],
encoder_depths: str = "3-3-3-3-3-3-8",
**kwargs
):
super().__init__(**kwargs)
self.channels = channels
self.corpus_normalize = corpus_normalize
self.causal = causal
self.vae_dim = vae_dim
self.fix_std = fix_std
self.std_dist_type = std_dist_type
# common parameters
self.conv_norm = conv_norm
self.pad_mode = pad_mode
self.layernorm_eps = layernorm_eps
self.disable_last_norm = disable_last_norm
self.layernorm = layernorm
self.layernorm_elementwise_affine = layernorm_elementwise_affine
self.conv_bias = conv_bias
self.layer_scale_init_value = layer_scale_init_value
self.weight_init_value = weight_init_value
self.mixer_layer = mixer_layer
# encoder specific parameters
self.encoder_n_filters = encoder_n_filters
self.encoder_ratios = encoder_ratios
self.encoder_depths = encoder_depths
class VibeVoiceDiffusionHeadConfig(PretrainedConfig):
model_type = "vibevoice_diffusion_head"
def __init__(
self,
hidden_size=768,
head_layers=4,
head_ffn_ratio=3.0,
rms_norm_eps=1e-5,
latent_size=64,
speech_vae_dim=None,
prediction_type="v_prediction",
diffusion_type="ddpm",
ddpm_num_steps=1000,
ddpm_num_inference_steps=20,
ddpm_beta_schedule="cosine",
ddpm_batch_mul=4,
**kwargs
):
self.hidden_size = hidden_size
self.head_layers = head_layers
self.head_ffn_ratio = head_ffn_ratio
self.rms_norm_eps = rms_norm_eps
self.latent_size = latent_size
self.speech_vae_dim = speech_vae_dim
self.prediction_type = prediction_type
self.diffusion_type = diffusion_type
self.ddpm_num_steps = ddpm_num_steps
self.ddpm_num_inference_steps = ddpm_num_inference_steps
self.ddpm_beta_schedule = ddpm_beta_schedule
self.ddpm_batch_mul = ddpm_batch_mul
super().__init__(**kwargs)
class VibeVoiceConfig(PretrainedConfig):
model_type = "vibevoice"
is_composition = True
sub_configs = {
"acoustic_tokenizer_config": VibeVoiceAcousticTokenizerConfig,
"semantic_tokenizer_config": VibeVoiceSemanticTokenizerConfig,
"decoder_config": Qwen2Config,
"diffusion_head_config": VibeVoiceDiffusionHeadConfig,
}
# keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen2`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
def __init__(
self,
acoustic_tokenizer_config=None,
semantic_tokenizer_config=None,
decoder_config=None,
diffusion_head_config=None,
**kwargs
):
# kwargs["_attn_implementation"] = "flash_attention_2"
kwargs["_attn_implementation_autoset"] = False
if acoustic_tokenizer_config is None:
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"]()
elif isinstance(acoustic_tokenizer_config, dict):
acoustic_tokenizer_config["model_type"] = "vibevoice_acoustic_tokenizer"
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"](**acoustic_tokenizer_config)
elif isinstance(acoustic_tokenizer_config, VibeVoiceAcousticTokenizerConfig):
# If an instance of the config class is provided
self.acoustic_tokenizer_config = acoustic_tokenizer_config
if semantic_tokenizer_config is None:
self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"]()
elif isinstance(semantic_tokenizer_config, dict):
semantic_tokenizer_config["model_type"] = "vibevoice_semantic_tokenizer"
self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"](**semantic_tokenizer_config)
elif isinstance(semantic_tokenizer_config, VibeVoiceSemanticTokenizerConfig):
# If an instance of the config class is provided
self.semantic_tokenizer_config = semantic_tokenizer_config
if decoder_config is None:
self.decoder_config = self.sub_configs["decoder_config"]()
elif isinstance(decoder_config, dict):
# If a dictionary is provided, instantiate the config class with it
# self.decoder_config = self.sub_configs["decoder_config"](**decoder_config)
if decoder_config.get("model_type", '') == "qwen2":
self.decoder_config = Qwen2Config(**decoder_config)
else:
raise ValueError(f"Unsupported decoder model type: {decoder_config.get('model_type', '')}")
elif isinstance(decoder_config, (Qwen2Config,)):
# If an instance of the config class is provided
self.decoder_config = decoder_config
if diffusion_head_config is None:
self.diffusion_head_config = self.sub_configs["diffusion_head_config"]()
elif isinstance(diffusion_head_config, dict):
diffusion_head_config["model_type"] = "vibevoice_diffusion_head"
self.diffusion_head_config = self.sub_configs["diffusion_head_config"](**diffusion_head_config)
elif isinstance(diffusion_head_config, VibeVoiceDiffusionHeadConfig):
# If an instance of the config class is provided
self.diffusion_head_config = diffusion_head_config
# other parameters
self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64)
self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, 'vae_dim', 128)
super().__init__(**kwargs)
def get_text_config(self, decoder=False):
"""
Returns the text config for this model.
vLLM uses this method to get the text configuration from multimodal models.
This allows vLLM to correctly determine hidden_size, num_attention_heads,
and other properties needed for memory profiling and model execution.
For VibeVoice, the "text config" is the decoder_config (Qwen2Config).
Args:
decoder: If True, return the decoder config (for encoder-decoder models).
For VibeVoice, this is always the decoder_config.
Returns:
The decoder configuration (Qwen2Config) which contains hidden_size, etc.
"""
return self.decoder_config
def to_dict(self):
"""
Override to_dict to handle torch.dtype serialization.
Fixes: https://github.com/microsoft/VibeVoice/issues/199
"""
output = super().to_dict()
return _convert_dtype_to_string(output)
class VibeVoiceASRConfig(PretrainedConfig):
model_type = "vibevoice"
is_composition = True
sub_configs = {
"acoustic_tokenizer_config": VibeVoiceAcousticTokenizerConfig,
"semantic_tokenizer_config": VibeVoiceSemanticTokenizerConfig,
"decoder_config": Qwen2Config,
}
# keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen2`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
def __init__(
self,
acoustic_tokenizer_config=None,
semantic_tokenizer_config=None,
decoder_config=None,
**kwargs
):
# kwargs["_attn_implementation"] = "flash_attention_2"
kwargs["_attn_implementation_autoset"] = False
if acoustic_tokenizer_config is None:
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"]()
elif isinstance(acoustic_tokenizer_config, dict):
acoustic_tokenizer_config["model_type"] = "vibevoice_acoustic_tokenizer"
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"](**acoustic_tokenizer_config)
elif isinstance(acoustic_tokenizer_config, VibeVoiceAcousticTokenizerConfig):
# If an instance of the config class is provided
self.acoustic_tokenizer_config = acoustic_tokenizer_config
if semantic_tokenizer_config is None:
self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"]()
elif isinstance(semantic_tokenizer_config, dict):
semantic_tokenizer_config["model_type"] = "vibevoice_semantic_tokenizer"
self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"](**semantic_tokenizer_config)
elif isinstance(semantic_tokenizer_config, VibeVoiceSemanticTokenizerConfig):
# If an instance of the config class is provided
self.semantic_tokenizer_config = semantic_tokenizer_config
if decoder_config is None:
self.decoder_config = self.sub_configs["decoder_config"]()
elif isinstance(decoder_config, dict):
# If a dictionary is provided, instantiate the config class with it
# self.decoder_config = self.sub_configs["decoder_config"](**decoder_config)
if decoder_config.get("model_type", '') == "qwen2":
self.decoder_config = Qwen2Config(**decoder_config)
else:
raise ValueError(f"Unsupported decoder model type: {decoder_config.get('model_type', '')}")
elif isinstance(decoder_config, Qwen2Config):
# If an instance of the config class is provided
self.decoder_config = decoder_config
# other parameters
self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64)
self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, 'vae_dim', 128)
super().__init__(**kwargs)
def to_dict(self):
"""
Override to_dict to handle torch.dtype serialization.
Fixes: https://github.com/microsoft/VibeVoice/issues/199
"""
output = super().to_dict()
return _convert_dtype_to_string(output)
def get_text_config(self, decoder: bool = False):
"""Return the text (decoder) config for generation."""
return self.decoder_config
@property
def vocab_size(self):
"""Return vocab_size from decoder config for generation compatibility."""
return self.decoder_config.vocab_size
@property
def num_attention_heads(self):
"""Return num_attention_heads from decoder config for Ulysses SP compatibility."""
return self.decoder_config.num_attention_heads
@property
def num_key_value_heads(self):
"""Return num_key_value_heads from decoder config for Ulysses SP compatibility."""
return self.decoder_config.num_key_value_heads
@property
def hidden_size(self):
"""Return hidden_size from decoder config for model compatibility."""
return self.decoder_config.hidden_size
@property
def num_hidden_layers(self):
"""Return num_hidden_layers from decoder config for Ulysses SP compatibility."""
return self.decoder_config.num_hidden_layers
@property
def head_dim(self):
"""Return head_dim from decoder config for Ulysses SP compatibility."""
return getattr(self.decoder_config, 'head_dim', self.hidden_size // self.num_attention_heads)
__all__ = [
"VibeVoiceAcousticTokenizerConfig",
"VibeVoiceSemanticTokenizerConfig",
"VibeVoiceDiffusionHeadConfig",
"VibeVoiceConfig",
"VibeVoiceASRConfig"
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/configuration_vibevoice.py",
"license": "MIT License",
"lines": 349,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/configuration_vibevoice_streaming.py | """ VibeVoice Streaming model configuration"""
import torch
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
from .configuration_vibevoice import VibeVoiceAcousticTokenizerConfig, VibeVoiceDiffusionHeadConfig, _convert_dtype_to_string
logger = logging.get_logger(__name__)
class VibeVoiceStreamingConfig(PretrainedConfig):
model_type = "vibevoice_streaming"
is_composition = True
sub_configs = {
"acoustic_tokenizer_config": VibeVoiceAcousticTokenizerConfig,
"decoder_config": Qwen2Config,
"diffusion_head_config": VibeVoiceDiffusionHeadConfig,
}
# keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen2`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
def __init__(
self,
acoustic_tokenizer_config=None,
decoder_config=None,
diffusion_head_config=None,
tts_backbone_num_hidden_layers=20,
**kwargs
):
# kwargs["_attn_implementation"] = "flash_attention_2"
kwargs["_attn_implementation_autoset"] = False
if acoustic_tokenizer_config is None:
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"]()
elif isinstance(acoustic_tokenizer_config, dict):
acoustic_tokenizer_config["model_type"] = "vibevoice_acoustic_tokenizer"
self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"](**acoustic_tokenizer_config)
elif isinstance(acoustic_tokenizer_config, VibeVoiceAcousticTokenizerConfig):
# If an instance of the config class is provided
self.acoustic_tokenizer_config = acoustic_tokenizer_config
if decoder_config is None:
self.decoder_config = self.sub_configs["decoder_config"]()
elif isinstance(decoder_config, dict):
# If a dictionary is provided, instantiate the config class with it
# self.decoder_config = self.sub_configs["decoder_config"](**decoder_config)
if decoder_config.get("model_type", '') == "qwen2":
self.decoder_config = Qwen2Config(**decoder_config)
else:
raise ValueError(f"Unsupported decoder model type: {decoder_config.get('model_type', '')}")
elif isinstance(decoder_config, (Qwen2Config,)):
# If an instance of the config class is provided
self.decoder_config = decoder_config
if diffusion_head_config is None:
self.diffusion_head_config = self.sub_configs["diffusion_head_config"]()
elif isinstance(diffusion_head_config, dict):
diffusion_head_config["model_type"] = "vibevoice_diffusion_head"
self.diffusion_head_config = self.sub_configs["diffusion_head_config"](**diffusion_head_config)
elif isinstance(diffusion_head_config, VibeVoiceDiffusionHeadConfig):
# If an instance of the config class is provided
self.diffusion_head_config = diffusion_head_config
# other parameters
self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64)
# The decoder of the model is divided into two components. The lower Transformer layers are only used for encoding text, while the upper Transformer layers are used for encoding text and generating speech. `tts_backbone_num_hidden_layers` indicates the number of upper layers used for TTS.
self.tts_backbone_num_hidden_layers = tts_backbone_num_hidden_layers
super().__init__(**kwargs)
def get_text_config(self, decoder=False):
"""Returns the decoder config (required for transformers >= 4.57 cache compatibility)."""
return self.decoder_config
@property
def num_hidden_layers(self):
"""Proxy to decoder_config.num_hidden_layers (required for transformers >= 4.57)."""
return self.decoder_config.num_hidden_layers
def to_dict(self):
"""
Override to_dict to handle torch.dtype serialization.
Fixes: https://github.com/microsoft/VibeVoice/issues/199
"""
output = super().to_dict()
return _convert_dtype_to_string(output)
__all__ = [
"VibeVoiceStreamingConfig"
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/configuration_vibevoice_streaming.py",
"license": "MIT License",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modeling_vibevoice_streaming.py | from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union, Callable
from tqdm import tqdm
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from transformers.models.auto import AutoModel, AutoModelForCausalLM
from transformers.activations import ACT2FN
from transformers.modeling_outputs import CausalLMOutput, BaseModelOutputWithPast, ModelOutput
from transformers.models.llama.modeling_llama import LlamaRMSNorm
from transformers import modeling_utils
from transformers.modeling_utils import PreTrainedModel
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.utils import logging
from .modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler
from .configuration_vibevoice_streaming import VibeVoiceStreamingConfig
logger = logging.get_logger(__name__)
if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
class BinaryClassifier(nn.Module):
def __init__(self, hidden_size):
super(BinaryClassifier, self).__init__()
self.fc1 = nn.Linear(hidden_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
class SpeechConnector(nn.Module):
def __init__(self, input_dim, output_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, output_dim)
self.norm = LlamaRMSNorm(output_dim, eps=1e-6)
self.fc2 = nn.Linear(output_dim, output_dim)
def forward(self, features, **kwargs):
x = self.fc1(features)
x = self.norm(x)
x = self.fc2(x)
return x
# @auto_docstring
class VibeVoiceStreamingPreTrainedModel(PreTrainedModel):
config_class = VibeVoiceStreamingConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_skip_keys_device_placement = "past_key_values"
_supports_cache_class = True
_supports_flash_attn_2 = True
_supports_sdpa = True
_supports_quantized_cache = True
_supports_static_cache = True
_supports_attention_backend = True
def _init_weights(self, module):
if isinstance(module, VibeVoiceDiffusionHead):
module.initialize_weights()
return
# Use the language model's initializer_range if available
if hasattr(self.config, 'language_model_config') and hasattr(self.config.language_model_config, 'initializer_range'):
std = self.config.language_model_config.initializer_range
elif hasattr(self.config, 'decoder_config') and hasattr(self.config.decoder_config, 'initializer_range'):
std = self.config.decoder_config.initializer_range
else:
std = 0.02 # Default value
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.weight.data.fill_(1.0)
module.bias.data.zero_()
# @auto_docstring
class VibeVoiceStreamingModel(VibeVoiceStreamingPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, 'torch_dtype') and config.torch_dtype is not None:
if isinstance(config.torch_dtype, str):
dtype = getattr(torch, config.torch_dtype)
else:
dtype = config.torch_dtype
else:
dtype = torch.float32
# Initialize Qwen2 model for language modeling.
# The lower Transformer layers are only used for encoding text, while the upper Transformer layers are used for encoding text and generating speech.
# To keep the code clean, we constructs two language models.
# The final norm layer of the first language_model is set to identity and will not be used in inference.
lm_config = copy.deepcopy(config.decoder_config)
lm_backbone_num_hidden_layers = getattr(lm_config, 'num_hidden_layers', 24) - config.tts_backbone_num_hidden_layers
lm_config.num_hidden_layers = lm_backbone_num_hidden_layers
self.language_model = AutoModel.from_config(lm_config)
self.language_model.norm = nn.Identity()
# We only need the Transformer layers here. Note that embed_tokens in tts_language_model is unused
tts_lm_config = copy.deepcopy(lm_config)
tts_lm_config.num_hidden_layers = config.tts_backbone_num_hidden_layers
self.tts_language_model = AutoModel.from_config(tts_lm_config)
# Marks the text that needs to be spoken by the TTS model.
self.tts_input_types = nn.Embedding(num_embeddings=2, embedding_dim=config.decoder_config.hidden_size)
# Initialize speech components if needed
self.acoustic_tokenizer = AutoModel.from_config(config.acoustic_tokenizer_config).to(dtype)
self.acoustic_connector = SpeechConnector(config.acoustic_vae_dim, lm_config.hidden_size).to(dtype)
# Register scaling factors as buffers - use 1D tensors for FSDP compatibility
self.register_buffer('speech_scaling_factor', torch.tensor(float('nan')))
self.register_buffer('speech_bias_factor', torch.tensor(float('nan')))
# Initialize prediction head for speech generation
self.prediction_head = AutoModel.from_config(config.diffusion_head_config).to(dtype)
# Initialize noise scheduler
self.noise_scheduler = DPMSolverMultistepScheduler(
num_train_timesteps=config.diffusion_head_config.ddpm_num_steps,
beta_schedule=config.diffusion_head_config.ddpm_beta_schedule,
prediction_type=config.diffusion_head_config.prediction_type
)
def get_input_embeddings(self):
if hasattr(self.language_model, 'embed_tokens'):
# If the language model has an embed_tokens attribute, return it
return self.language_model.embed_tokens
for name, attr in self.language_model.fullmap.items(): # parallel by nnscaler, the name is changed
if attr.orig_name == 'embed_tokens.weight':
return getattr(self.language_model, name)
assert False, 'should not arrive here'
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def set_speech_tokenizers(self, acoustic_tokenizer=None):
"""Set the speech tokenizers used for encoding and decoding speech."""
self.acoustic_tokenizer = acoustic_tokenizer
# Reset the encoder to evaluation mode
if self.acoustic_tokenizer is not None:
self.acoustic_tokenizer.eval()
def forward(self, *args, **kwargs):
"""
Intentionally not implemented.
This streaming model is split into two explicit submodules:
- `language_model` for plain text processing (lower layers).
- `tts_language_model` for TTS-related upper layers.
We deliberately avoid a unified `forward` to prevent accidental calls
that mix responsibilities.
To use the model:
- Call `self.language_model(...)` for text embeddings / hidden states.
- Call `self.tts_language_model(...)` for the TTS portion.
- Use the dedicated inference class for combined generation logic.
"""
raise RuntimeError(
"VibeVoiceStreamingModel.forward is intentionally disabled. "
"Use `model.language_model(...)` or `model.tts_language_model(...)` instead."
)
AutoModel.register(VibeVoiceStreamingConfig, VibeVoiceStreamingModel)
__all__ = [
"VibeVoiceStreamingPreTrainedModel",
"VibeVoiceStreamingModel",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modeling_vibevoice_streaming.py",
"license": "MIT License",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modeling_vibevoice_streaming_inference.py | from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union, Callable
from tqdm import tqdm
import inspect
import torch
import torch.nn as nn
from transformers.models.auto import AutoModel, AutoModelForCausalLM
from transformers.generation import GenerationMixin, GenerationConfig, LogitsProcessor, LogitsProcessorList, StoppingCriteriaList
from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
from transformers import modeling_utils
from transformers.modeling_utils import PreTrainedModel
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.utils import logging
from .modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache
from .modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler
from .configuration_vibevoice_streaming import VibeVoiceStreamingConfig
from .modular_vibevoice_text_tokenizer import VibeVoiceTextTokenizer, VibeVoiceTextTokenizerFast
from .modeling_vibevoice_streaming import VibeVoiceStreamingPreTrainedModel, VibeVoiceStreamingModel, BinaryClassifier
from .streamer import AudioStreamer, AsyncAudioStreamer
logger = logging.get_logger(__name__)
if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
TTS_TEXT_WINDOW_SIZE = 5
TTS_SPEECH_WINDOW_SIZE = 6
# ============================================================================
# Transformers >= 4.57 Compatibility Layer
# The cache system was refactored in transformers 4.57, requiring these helpers.
# ============================================================================
class MockCacheLayer:
"""
Mock cache layer for transformers >= 4.57 compatibility.
Provides the `layers` interface expected by DynamicCache in newer versions.
"""
def __init__(self, key_cache, value_cache, parent_cache=None, layer_idx=0):
self.key_cache = key_cache
self.value_cache = value_cache
self._parent_cache = parent_cache
self._layer_idx = layer_idx
def get_mask_sizes(self, cache_position):
"""Return KV length and offset for mask creation."""
kv_length = self.key_cache.shape[2] if self.key_cache is not None else 0
return kv_length, 0
def update(self, key_states, value_states, cache_kwargs=None):
"""Update the cache with new key/value states."""
if self._parent_cache is None:
return self.key_cache, self.value_cache
parent = self._parent_cache
idx = self._layer_idx
# Extend cache lists if needed
while len(parent.key_cache) <= idx:
parent.key_cache.append(None)
parent.value_cache.append(None)
# Concatenate or initialize cache
if parent.key_cache[idx] is not None:
parent.key_cache[idx] = torch.cat([parent.key_cache[idx], key_states], dim=2)
parent.value_cache[idx] = torch.cat([parent.value_cache[idx], value_states], dim=2)
else:
parent.key_cache[idx] = key_states
parent.value_cache[idx] = value_states
# Update local references
self.key_cache = parent.key_cache[idx]
self.value_cache = parent.value_cache[idx]
return self.key_cache, self.value_cache
def _ensure_cache_has_layers(cache):
"""
Ensure the cache has all required attributes for transformers >= 4.57.
Creates MockCacheLayer wrappers to provide the expected `layers` interface.
"""
if cache is None:
return cache
# Add required attributes (skip if read-only)
for attr, default in [('layer_class_to_replicate', None), ('offloading', False), ('is_compileable', False)]:
if not hasattr(cache, attr):
try:
setattr(cache, attr, default)
except AttributeError:
pass
# Build layers list from key_cache/value_cache
if hasattr(cache, 'key_cache') and hasattr(cache, 'value_cache'):
try:
cache.layers = [
MockCacheLayer(cache.key_cache[i], cache.value_cache[i], parent_cache=cache, layer_idx=i)
for i in range(len(cache.key_cache))
]
except AttributeError:
pass
elif not hasattr(cache, 'layers'):
try:
cache.layers = []
except AttributeError:
pass
return cache
def _update_model_kwargs_for_generation(
outputs: ModelOutput,
model_kwargs: Dict[str, Any],
num_new_tokens: int = 1,
) -> Dict[str, Any]:
"""
Update model_kwargs after adding new tokens (supports multi-token windows).
Updates past_key_values, attention_mask, and cache_position for the next forward pass.
"""
model_kwargs["past_key_values"] = _ensure_cache_has_layers(outputs.past_key_values)
attention_mask = model_kwargs["attention_mask"]
model_kwargs["attention_mask"] = torch.cat(
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], num_new_tokens))], dim=-1
)
cache_pos = model_kwargs["cache_position"]
model_kwargs["cache_position"] = torch.arange(
cache_pos[-1] + 1, cache_pos[-1] + num_new_tokens + 1, device=cache_pos.device
)
return model_kwargs
@dataclass
class VibeVoiceCausalLMOutputWithPast(BaseModelOutputWithPast):
logits: Optional[torch.FloatTensor] = None
@dataclass
class VibeVoiceGenerationOutput(ModelOutput):
"""
Output type for VibeVoice generation.
Args:
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
The generated sequences.
speech_outputs (`List[torch.FloatTensor]`, *optional*):
List of generated speech waveforms or latents for each speech segment.
"""
sequences: torch.LongTensor = None
speech_outputs: Optional[List[torch.FloatTensor]] = None
reach_max_step_sample: Optional[torch.BoolTensor] = None
class VibeVoiceStreamingForConditionalGenerationInference(VibeVoiceStreamingPreTrainedModel, GenerationMixin):
def __init__(self, config):
super().__init__(config)
# Initialize the base model
self.model = VibeVoiceStreamingModel(config)
# TTS generation EOS classifier
self.tts_eos_classifier = BinaryClassifier(config.decoder_config.hidden_size)
# inference configuration
self.ddpm_inference_steps = config.diffusion_head_config.ddpm_num_inference_steps
# Initialize weights and apply final processing
self.post_init()
@property
def noise_scheduler(self):
return self.model.noise_scheduler
@property
def prediction_head(self):
return self.model.prediction_head
@property
def speech_scaling_factor(self):
return self.model.speech_scaling_factor
@property
def speech_bias_factor(self):
return self.model.speech_bias_factor
@property
def acoustic_tokenizer(self):
return self.model.acoustic_tokenizer
@property
def acoustic_connector(self):
return self.model.acoustic_connector
def tie_weights(self):
"""
Tie the weights between the input embeddings and the output embeddings.
"""
# Tie lm_head.weight to language_model.embed_tokens.weight
if not getattr(self.config, 'tie_word_embeddings', False):
return
if hasattr(self, 'lm_head') and hasattr(self.model.language_model, 'embed_tokens'):
self.lm_head.weight = self.model.language_model.embed_tokens.weight
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def get_output_embeddings(self):
"""
This model does not define an `lm_head` (vocabulary projection).
"""
return None
def set_output_embeddings(self, new_embeddings):
"""
No-op because there is no `lm_head`. Provided only to satisfy optional API calls.
To enable, first create `self.lm_head` then allow assignment.
"""
raise RuntimeError("Output embeddings (lm_head) are not defined for this model. "
"Create one before calling set_output_embeddings if needed.")
def set_speech_tokenizers(self, acoustic_tokenizer=None):
"""Set the speech tokenizers used for encoding and decoding speech."""
self.model.set_speech_tokenizers(acoustic_tokenizer)
def set_ddpm_inference_steps(self, num_steps=None):
self.ddpm_inference_steps = num_steps or self.config.diffusion_head_config.ddpm_num_inference_steps
def prepare_inputs_for_generation(
self,
input_ids: torch.LongTensor,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
**kwargs,
):
"""Prepare model inputs for generation (transformers >= 4.57 compatible)."""
model_inputs = {"cache_position": cache_position}
# Slice inputs when using cache
if past_key_values is not None:
model_inputs["past_key_values"] = past_key_values
if inputs_embeds is not None and input_ids.shape[1] == 0:
inputs_embeds = inputs_embeds[:, -cache_position.shape[0]:]
elif inputs_embeds is not None or (cache_position is not None and cache_position[-1] >= input_ids.shape[1]):
input_ids = input_ids[:, -cache_position.shape[0]:]
elif cache_position is not None and input_ids.shape[1] != cache_position.shape[0]:
input_ids = input_ids[:, cache_position]
# Set input_ids or inputs_embeds
use_embeds = inputs_embeds is not None and (
past_key_values is None or (cache_position is not None and len(cache_position) == inputs_embeds.shape[1])
)
if use_embeds:
model_inputs["input_ids"] = None
model_inputs["inputs_embeds"] = inputs_embeds
else:
model_inputs["input_ids"] = input_ids.clone(memory_format=torch.contiguous_format) if input_ids is not None else None
model_inputs["inputs_embeds"] = None
if attention_mask is not None:
model_inputs["attention_mask"] = attention_mask
# Create position_ids from attention_mask
if attention_mask is not None and kwargs.get("position_ids") is None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
kwargs["position_ids"] = position_ids
# Slice position_ids when using cache
if kwargs.get("position_ids") is not None:
if past_key_values is not None:
seq_len = model_inputs["inputs_embeds"].shape[1] if model_inputs.get("inputs_embeds") is not None else model_inputs["input_ids"].shape[1]
model_inputs["position_ids"] = kwargs["position_ids"][:, -seq_len:].clone(memory_format=torch.contiguous_format)
else:
model_inputs["position_ids"] = kwargs.pop("position_ids").clone(memory_format=torch.contiguous_format)
# Forward remaining kwargs
for key, value in kwargs.items():
if key not in model_inputs:
model_inputs[key] = value
model_inputs.pop("labels", None)
return model_inputs
def _update_model_kwargs_for_generation(
self,
outputs,
model_kwargs,
is_encoder_decoder=False,
num_new_tokens=1,
):
"""Override to ensure cache compatibility with transformers >= 4.57."""
model_kwargs = super()._update_model_kwargs_for_generation(
outputs, model_kwargs, is_encoder_decoder=is_encoder_decoder, num_new_tokens=num_new_tokens
)
if "past_key_values" in model_kwargs:
model_kwargs["past_key_values"] = _ensure_cache_has_layers(model_kwargs["past_key_values"])
return model_kwargs
def _init_cache_for_generation(self, generation_config, model_kwargs, batch_size, max_cache_length, device):
"""
Initialize cache for generation, handling different transformers versions.
For transformers >= 4.57, returns None to let the model create the cache dynamically.
"""
try:
from transformers.cache_utils import DynamicCache
sig = inspect.signature(DynamicCache.__init__)
if 'config' in sig.parameters:
# transformers >= 4.57: let model handle cache creation
return None
else:
# Older versions: use parent method
prep_sig = inspect.signature(self._prepare_cache_for_generation)
if 'device' in prep_sig.parameters:
self._prepare_cache_for_generation(generation_config, model_kwargs, None, batch_size, max_cache_length, device)
else:
self._prepare_cache_for_generation(generation_config, model_kwargs, None, batch_size, max_cache_length)
return model_kwargs.get("past_key_values")
except Exception:
return None
# @can_return_tuple
def forward_lm(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> Union[Tuple, BaseModelOutputWithPast]:
"""
Single pass of the base text LM.
- Builds embeddings if `inputs_embeds` not provided.
- Uses (and returns) `past_key_values` when `use_cache=True`.
- No loss / no lm_head / no speech logic.
Args:
input_ids: (B, S) token ids.
attention_mask: (B, S) mask.
past_key_values: cache from previous steps.
cache_position: positions for cached tokens.
labels: unsupported (will raise).
Returns:
BaseModelOutputWithPast with `last_hidden_state` and `past_key_values`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Get embeddings
if inputs_embeds is None:
inputs_embeds = self.model.get_input_embeddings()(input_ids)
outputs = self.model.language_model(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
if labels is not None:
raise NotImplementedError("Loss computation is not implemented in this version.")
return BaseModelOutputWithPast(
past_key_values=outputs.past_key_values,
last_hidden_state=hidden_states,
attentions=outputs.attentions,
)
# @can_return_tuple
def forward_tts_lm(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
lm_last_hidden_state: Optional[torch.FloatTensor] = None,
tts_text_masks: Optional[torch.BoolTensor] = None,
**kwargs,
) -> Union[Tuple, VibeVoiceCausalLMOutputWithPast]:
"""
Single pass of the TTS LM.
- Overwrites tail embeddings with `lm_last_hidden_state`.
- Adds type embedding via `tts_text_masks` (1=text, 0=speech).
- Predicts EOS from last hidden state (binary classifier).
- No loss / no full acoustic decoding here.
Args:
input_ids: (B, S) token ids.
attention_mask: (B, S) mask.
lm_last_hidden_state: (B, K, H) hidden states to splice into the tail.
tts_text_masks: (B, 1) mask marking current position as text(1)/speech(0).
past_key_values: cache from previous TTS steps.
cache_position: positions for cached tokens.
labels: unsupported (will raise).
Returns:
VibeVoiceCausalLMOutputWithPast with `logits` (EOS), `last_hidden_state`, `past_key_values`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Get embeddings
if inputs_embeds is None:
# Will be replaced with lm_last_hidden_state
inputs_embeds = self.model.get_input_embeddings()(input_ids)
# Replace the last part of inputs_embeds with lm_last_hidden_state
start_idx = inputs_embeds.shape[1] - lm_last_hidden_state.shape[1]
inputs_embeds[:, start_idx:, :] = lm_last_hidden_state
# Adds type embedding via `tts_text_masks`.
inputs_embeds = inputs_embeds + self.model.tts_input_types(tts_text_masks.long())
outputs = self.model.tts_language_model(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
logits = self.tts_eos_classifier(hidden_states[:, -1, :])
if labels is not None:
raise NotImplementedError("Loss computation is not implemented in this version.")
return VibeVoiceCausalLMOutputWithPast(
logits=logits,
past_key_values=outputs.past_key_values,
last_hidden_state=hidden_states,
attentions=outputs.attentions,
)
def forward(self, *args, **kwargs):
"""
Unified forward is intentionally disabled.
Reasons:
1. The inference pipeline is staged: base text LM, then TTS LM, plus streaming & diffusion handled in `generate`.
2. A monolithic call would hide required sequencing (prefill, window stepping, speech diffusion sampling).
Use instead:
- self.forward_lm(...) for a base text LM step (prefill or incremental).
- self.forward_tts_lm(...) for a single TTS LM step (needs LM hidden states).
- self.generate(...) for full streaming (text + speech + diffusion + audio assembly).
Raises:
RuntimeError: Always (by design).
"""
raise RuntimeError(
"Unified forward is disabled. Use `forward_lm`, `forward_tts_lm`, or `generate` instead."
)
def _build_generate_config_model_kwargs(self, generation_config, inputs, tokenizer, return_processors=False, **kwargs):
if generation_config is None:
generation_config = GenerationConfig(
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
pad_token_id = tokenizer.pad_token_id
)
else:
generation_config = GenerationConfig(
**generation_config,
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
pad_token_id = tokenizer.pad_token_id
)
generation_config, model_kwargs = self._prepare_generation_config(
generation_config,
True,
speech_start_id=tokenizer.speech_start_id,
speech_end_id=tokenizer.speech_end_id,
speech_diffusion_id=tokenizer.speech_diffusion_id,
**kwargs
)
generation_config.speech_start_id = tokenizer.speech_start_id
generation_config.speech_end_id = tokenizer.speech_end_id
generation_config.speech_diffusion_id = tokenizer.speech_diffusion_id
inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(inputs, generation_config.bos_token_id, model_kwargs)
batch_size = inputs_tensor.shape[0]
device = self.device
self._prepare_special_tokens(generation_config, True, device=device)
generation_config.use_cache = True
model_kwargs["use_cache"] = generation_config.use_cache
input_ids = inputs_tensor.to(self.device)
input_ids_length = input_ids.shape[1]
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
generation_config = self._prepare_generated_length(
generation_config=generation_config,
has_default_max_length=has_default_max_length,
has_default_min_length=has_default_min_length,
model_input_name=model_input_name,
inputs_tensor=inputs_tensor,
input_ids_length=input_ids_length,
)
max_cache_length = generation_config.max_length - 1
# Handle cache initialization for different transformers versions
model_kwargs["past_key_values"] = self._init_cache_for_generation(
generation_config, model_kwargs, batch_size, max_cache_length, device
)
model_kwargs['cache_position'] = torch.arange(input_ids_length, device=device, dtype=torch.long)
for k, v in model_kwargs.items():
if isinstance(v, torch.Tensor):
model_kwargs[k] = v.to(device=device)
if return_processors:
logits_processor = self._get_logits_processor(
generation_config=generation_config,
input_ids_seq_length=input_ids_length,
encoder_input_ids=inputs_tensor,
prefix_allowed_tokens_fn=None,
logits_processor=LogitsProcessorList(),
device=inputs_tensor.device,
model_kwargs=model_kwargs,
)
stopping_criteria = self._get_stopping_criteria(generation_config=generation_config, stopping_criteria=StoppingCriteriaList())
return generation_config, model_kwargs, input_ids, logits_processor, stopping_criteria
else:
return generation_config, model_kwargs, input_ids
@torch.no_grad()
def generate(
self,
inputs: Optional[torch.Tensor] = None,
generation_config: Optional[GenerationConfig] = None,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
synced_gpus: Optional[bool] = None,
assistant_model: Optional["PreTrainedModel"] = None,
audio_streamer: Optional[Union[AudioStreamer, AsyncAudioStreamer]] = None,
negative_prompt_ids: Optional[torch.Tensor] = None,
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
speech_tensors: Optional[torch.FloatTensor] = None,
speech_masks: Optional[torch.BoolTensor] = None,
speech_input_mask: Optional[torch.BoolTensor] = None,
tts_text_ids: Optional[torch.LongTensor] = None,
return_speech: bool = True,
cfg_scale: float = 1.0,
stop_check_fn: Optional[Callable[[], bool]] = None,
**kwargs,
) -> Union[torch.LongTensor, VibeVoiceGenerationOutput]:
"""
Text is fed in small windows (dynamic slicing of `tts_text_ids`), which enables streaming text input: you don’t need the full text upfront. After each text window, a loop samples several speech latents (diffusion). The interleaved text encoding + speech generation enables streaming text input and realtime speech output.
The function only supports batch size = 1 currently.
- Windowed text prefill → incremental LM + TTS LM updates.
- Interleave speech token diffusion sampling (`sample_speech_tokens`).
- Stops on EOS (binary classifier) or max length / external `stop_check_fn`.
- Returns final token `sequences` and (optionally) concatenated speech audio.
Args (selected):
tts_text_ids: Full text tokens to stream in windows.
audio_streamer: If provided, emits audio chunks during generation.
cfg_scale: Classifier-free guidance scale for speech diffusion.
return_speech: If False, skips audio decode concatenation.
stop_check_fn: External early-stop hook (returns True to halt).
Returns:
VibeVoiceGenerationOutput with:
- sequences: final token ids
- speech_outputs: list of concatenated audio tensors (or None)
- reach_max_step_sample: flags for samples stopped by max length
"""
# 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
tokenizer = kwargs.pop("tokenizer", None)
neg_text_input_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
tts_lm_input_ids = kwargs.pop("tts_lm_input_ids", None)
tts_lm_attention_mask = kwargs.pop("tts_lm_attention_mask", None)
# all_prefilled_outputs: cached prefilled prompt outputs for lm, tts_lm, neg_lm, neg_tts_lm
all_prefilled_outputs = kwargs.pop("all_prefilled_outputs", None)
tts_text_ids = tts_text_ids.to(self.device)
if kwargs.get('max_new_tokens', None) is None:
kwargs['max_new_tokens'] = self.config.decoder_config.max_position_embeddings - tts_lm_input_ids.shape[-1]
generation_config, model_kwargs, input_ids, logits_processor, stopping_criteria = self._build_generate_config_model_kwargs(
generation_config, inputs, tokenizer, return_processors=True, **kwargs
)
negative_kwargs = {
'input_ids': torch.full((kwargs['input_ids'].shape[0], 1), neg_text_input_id, dtype=torch.long, device=kwargs['input_ids'].device),
'attention_mask': torch.ones((kwargs['input_ids'].shape[0], 1), dtype=torch.long, device=kwargs['input_ids'].device),
'max_new_tokens': kwargs.get('max_new_tokens', 100)
}
negative_generation_config, negative_model_kwargs, negative_input_ids = self._build_generate_config_model_kwargs(
None, None, tokenizer, return_processors=False, **negative_kwargs
)
tts_lm_kwargs = {
'input_ids': tts_lm_input_ids,
'attention_mask': tts_lm_attention_mask,
'max_new_tokens': kwargs.get('max_new_tokens', 100)
}
tts_lm_generation_config, tts_lm_model_kwargs, tts_lm_input_ids = self._build_generate_config_model_kwargs(
None, None, tokenizer, return_processors=False, **tts_lm_kwargs
)
tts_lm_negative_kwargs = {
'input_ids': torch.full((kwargs['input_ids'].shape[0], 1), neg_text_input_id, dtype=torch.long, device=kwargs['input_ids'].device),
'attention_mask': torch.ones((kwargs['input_ids'].shape[0], 1), dtype=torch.long, device=kwargs['input_ids'].device),
'max_new_tokens': kwargs.get('max_new_tokens', 100)
}
tts_lm_negative_generation_config, tts_lm_negative_model_kwargs, tts_lm_negative_input_ids = self._build_generate_config_model_kwargs(
None, None, tokenizer, return_processors=False, **tts_lm_negative_kwargs
)
acoustic_cache = VibeVoiceTokenizerStreamingCache()
batch_size = input_ids.shape[0]
assert batch_size == 1, "Currently only supports batch size == 1"
device = input_ids.device
finished_tags = torch.zeros(batch_size, dtype=torch.bool, device=device)
verbose = kwargs.get("verbose", False)
# Initialize audio chunks storage for each sample
audio_chunks = [[] for _ in range(batch_size)]
tts_text_window_index = 0
reach_max_step_sample = torch.zeros(batch_size, dtype=torch.bool, device=device)
first_text_window_size = TTS_TEXT_WINDOW_SIZE if tts_text_ids.shape[1] >= TTS_TEXT_WINDOW_SIZE else tts_text_ids.shape[1]
outputs = all_prefilled_outputs["lm"]
tts_lm_outputs = all_prefilled_outputs["tts_lm"]
negative_outputs = all_prefilled_outputs["neg_lm"]
tts_lm_negative_outputs = all_prefilled_outputs["neg_tts_lm"]
model_kwargs = _update_model_kwargs_for_generation(
outputs, model_kwargs, num_new_tokens=first_text_window_size,
)
tts_lm_model_kwargs = _update_model_kwargs_for_generation(
tts_lm_outputs, tts_lm_model_kwargs, num_new_tokens=first_text_window_size,
)
negative_model_kwargs = self._update_model_kwargs_for_generation(
negative_outputs, negative_model_kwargs, is_encoder_decoder=False,
)
tts_lm_negative_model_kwargs = self._update_model_kwargs_for_generation(
tts_lm_negative_outputs, tts_lm_negative_model_kwargs, is_encoder_decoder=False,
)
step = tts_lm_input_ids.shape[1]
total_generated_speech_tokens = 0
total_prefilled_text_tokens = 0
if kwargs.get("show_progress_bar", True):
progress_bar = tqdm(
total=tts_lm_generation_config.max_length,
desc=f"Prefilled {step} tokens, current step ({step} / {tts_lm_generation_config.max_length})",
initial=step,
leave=False
)
else:
progress_bar = None
while True:
# Check for external stop signal
if stop_check_fn is not None and stop_check_fn():
if verbose:
print(f"Generation stopped externally at step {step + 1}")
# End the audio streamer if it exists
if audio_streamer is not None:
audio_streamer.end()
break
# # Check if audio_streamer has been ended (stopped externally)
# if audio_streamer is not None and hasattr(audio_streamer, 'finished_flags'):
# if any(audio_streamer.finished_flags):
# if verbose:
# print(f"Audio generation stopped externally at step {step + 1}")
# break
if finished_tags.all():
if hasattr(progress_bar, 'set_description'):
progress_bar.set_description("Generation complete")
break
cur_input_tts_text_ids = tts_text_ids[:, tts_text_window_index*TTS_TEXT_WINDOW_SIZE:(tts_text_window_index+1)*TTS_TEXT_WINDOW_SIZE]
next_text_window_size = tts_text_ids[:, (tts_text_window_index+1)*TTS_TEXT_WINDOW_SIZE:(tts_text_window_index+2)*TTS_TEXT_WINDOW_SIZE].shape[1]
tts_text_window_index += 1
if cur_input_tts_text_ids.shape[1] > 0:
input_ids = torch.cat([input_ids, cur_input_tts_text_ids], dim=-1)
tts_lm_input_ids = torch.cat([tts_lm_input_ids, cur_input_tts_text_ids], dim=-1)
if tts_lm_input_ids.shape[1] > tts_lm_generation_config.max_length:
if verbose:
print(f"Reached maximum generation length {generation_config.max_length}, stopped it.")
reached_samples = torch.arange(batch_size, device=device)[~finished_tags]
if reached_samples.numel() > 0:
reach_max_step_sample[reached_samples] = True
break
step += cur_input_tts_text_ids.shape[1]
total_prefilled_text_tokens += cur_input_tts_text_ids.shape[1]
if progress_bar is not None:
progress_bar.update(cur_input_tts_text_ids.shape[1])
progress_bar.set_description(f"Prefilled {total_prefilled_text_tokens} text tokens, generated {total_generated_speech_tokens} speech tokens, current step ({step} / {tts_lm_generation_config.max_length})")
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
# Forward pass through the model
outputs = self.forward_lm(
**model_inputs, return_dict=True, output_attentions=False, output_hidden_states=False,
)
model_kwargs = _update_model_kwargs_for_generation(
outputs, model_kwargs, num_new_tokens=next_text_window_size,
)
tts_lm_model_inputs = self.prepare_inputs_for_generation(tts_lm_input_ids, **tts_lm_model_kwargs)
tts_lm_additional_inputs = {
"tts_text_masks": torch.ones_like(tts_lm_input_ids[:, -1:]),
"lm_last_hidden_state": outputs.last_hidden_state,
}
# Forward pass through the model
tts_lm_outputs = self.forward_tts_lm(
**tts_lm_model_inputs, **tts_lm_additional_inputs, return_dict=True, output_attentions=False, output_hidden_states=False,
)
tts_lm_model_kwargs = self._update_model_kwargs_for_generation(
tts_lm_outputs, tts_lm_model_kwargs, is_encoder_decoder=False,
)
diffusion_indices = torch.LongTensor([0])
for cur_speech_index in range(TTS_SPEECH_WINDOW_SIZE):
positive_condition = tts_lm_outputs.last_hidden_state[diffusion_indices, -1, :]
negative_condition = tts_lm_negative_outputs.last_hidden_state[diffusion_indices, -1, :]
speech_latent = self.sample_speech_tokens(
positive_condition,
negative_condition,
cfg_scale=cfg_scale,
).unsqueeze(1)
# Decode acoustic latent to audio using acoustic streaming cache
scaled_latent = speech_latent / self.model.speech_scaling_factor.to(speech_latent.device) - self.model.speech_bias_factor.to(speech_latent.device)
audio_chunk = self.model.acoustic_tokenizer.decode(
scaled_latent.to(self.model.acoustic_tokenizer.device),
cache=acoustic_cache, # Use acoustic-specific cache
sample_indices=diffusion_indices.to(self.model.acoustic_tokenizer.device),
use_cache=True,
debug=False
)
# Store audio chunks for each sample
for i, sample_idx in enumerate(diffusion_indices):
idx = sample_idx.item()
# Only append audio chunk if the sample is not finished
if not finished_tags[idx]:
audio_chunks[idx].append(audio_chunk[i])
# Add streaming support here
if audio_streamer is not None:
# Stream the audio chunks immediately
audio_streamer.put(audio_chunk, diffusion_indices)
acoustic_embed = self.model.acoustic_connector(speech_latent)
tts_lm_input_ids = torch.cat([tts_lm_input_ids, torch.ones_like(tts_lm_input_ids[:, -1:])], dim=-1)
if tts_lm_input_ids.shape[1] > tts_lm_generation_config.max_length:
break
step += 1
total_generated_speech_tokens += 1
if progress_bar is not None:
progress_bar.update(1)
progress_bar.set_description(f"Prefilled {total_prefilled_text_tokens} text tokens, generated {total_generated_speech_tokens} speech tokens, current step ({step} / {tts_lm_generation_config.max_length})")
tts_lm_model_inputs = self.prepare_inputs_for_generation(tts_lm_input_ids, **tts_lm_model_kwargs)
tts_lm_additional_inputs = {
"tts_text_masks": torch.zeros_like(tts_lm_input_ids[:, -1:]),
"lm_last_hidden_state": acoustic_embed,
}
# Forward pass through the model
tts_lm_outputs = self.forward_tts_lm(
**tts_lm_model_inputs, **tts_lm_additional_inputs, return_dict=True, output_attentions=False, output_hidden_states=False,
)
if cur_speech_index == TTS_SPEECH_WINDOW_SIZE - 1 and next_text_window_size > 0:
tts_lm_model_kwargs = _update_model_kwargs_for_generation(
tts_lm_outputs, tts_lm_model_kwargs, num_new_tokens=next_text_window_size,
)
else:
tts_lm_model_kwargs = self._update_model_kwargs_for_generation(
tts_lm_outputs, tts_lm_model_kwargs, is_encoder_decoder=False,
)
tts_lm_negative_input_ids = torch.cat([tts_lm_negative_input_ids, torch.ones_like(tts_lm_input_ids[:, -1:])], dim=-1)
tts_lm_negative_model_inputs = self.prepare_inputs_for_generation(tts_lm_negative_input_ids, **tts_lm_negative_model_kwargs)
# Forward negative pass through the model
tts_lm_negative_additional_inputs = {
"tts_text_masks": torch.zeros_like(tts_lm_negative_input_ids[:, -1:]),
"lm_last_hidden_state": acoustic_embed,
}
tts_lm_negative_outputs = self.forward_tts_lm(
**tts_lm_negative_model_inputs, **tts_lm_negative_additional_inputs, return_dict=True, output_attentions=False, output_hidden_states=False,
)
tts_lm_negative_model_kwargs = self._update_model_kwargs_for_generation(
tts_lm_negative_outputs, tts_lm_negative_model_kwargs, is_encoder_decoder=False,
)
tts_eos_logits = torch.sigmoid(self.tts_eos_classifier(tts_lm_outputs.last_hidden_state[diffusion_indices, -1, :]))
if tts_eos_logits[0].item() > 0.5:
# If EOS token is predicted, we can stop generation for this sample
finished_tags[diffusion_indices] = True
if audio_streamer is not None:
audio_streamer.end(diffusion_indices)
if tts_lm_input_ids.shape[1] > tts_lm_generation_config.max_length:
if verbose:
print(f"Reached maximum generation length {tts_lm_generation_config.max_length}, stopped it.")
reached_samples = torch.arange(batch_size, device=device)[~finished_tags]
if reached_samples.numel() > 0:
reach_max_step_sample[reached_samples] = True
break
if audio_streamer is not None:
audio_streamer.end()
# Concatenate audio chunks for each sample
final_audio_outputs = []
for sample_chunks in audio_chunks:
if sample_chunks:
# Concatenate all chunks along the time dimension (assumed to be the last dimension)
concatenated_audio = torch.cat(sample_chunks, dim=-1)
final_audio_outputs.append(concatenated_audio)
else:
# If no audio was generated for this sample, append None
final_audio_outputs.append(None)
if reach_max_step_sample is not None and reach_max_step_sample.any():
print(f"Reached maximum generation length {tts_lm_generation_config.max_length}, stopped it.")
return VibeVoiceGenerationOutput(
sequences=tts_lm_input_ids,
speech_outputs=final_audio_outputs if return_speech else None,
reach_max_step_sample=reach_max_step_sample,
)
@torch.no_grad()
def sample_speech_tokens(self, condition, neg_condition, cfg_scale=3.0):
self.model.noise_scheduler.set_timesteps(self.ddpm_inference_steps)
condition = torch.cat([condition, neg_condition], dim=0).to(self.model.prediction_head.device)
speech = torch.randn(condition.shape[0], self.config.acoustic_vae_dim).to(condition)
for t in self.model.noise_scheduler.timesteps:
half = speech[: len(speech) // 2]
combined = torch.cat([half, half], dim=0)
eps = self.model.prediction_head(combined, t.repeat(combined.shape[0]).to(combined), condition=condition)
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
eps = torch.cat([half_eps, half_eps], dim=0)
speech = self.model.noise_scheduler.step(eps, t, speech).prev_sample
return speech[: len(speech) // 2]
AutoModelForCausalLM.register(VibeVoiceStreamingConfig, VibeVoiceStreamingForConditionalGenerationInference)
__all__ = [
"VibeVoiceStreamingForConditionalGenerationInference",
]
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modeling_vibevoice_streaming_inference.py",
"license": "MIT License",
"lines": 766,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modular_vibevoice_diffusion_head.py | import math
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.auto import AutoModel
from transformers.modeling_utils import PreTrainedModel
# from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.activations import ACT2FN
from transformers.utils import logging
from .configuration_vibevoice import VibeVoiceDiffusionHeadConfig
logger = logging.get_logger(__name__)
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine=True, memory_efficient=False):
super().__init__()
self.dim = dim
self.eps = eps
self.elementwise_affine = elementwise_affine
if self.elementwise_affine:
self.weight = nn.Parameter(torch.ones(dim))
else:
self.register_parameter('weight', None)
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float()).type_as(x)
if self.weight is not None:
output = output * self.weight
return output
def extra_repr(self) -> str:
return f'dim={self.dim}, eps={self.eps}, elementwise_affine={self.elementwise_affine}'
def modulate(x, shift, scale):
"""Apply modulation to input tensor."""
return x * (1 + scale) + shift
class TimestepEmbedder(nn.Module):
"""
Embeds scalar timesteps into vector representations.
Args:
hidden_size (`int`): Size of the output embedding
frequency_embedding_size (`int`, optional): Size of the intermediate frequency embedding
"""
def __init__(self, hidden_size, frequency_embedding_size=256):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=False),
# nn.SiLU(),
ACT2FN['silu'],
nn.Linear(hidden_size, hidden_size, bias=False),
)
self.frequency_embedding_size = frequency_embedding_size
@staticmethod
def timestep_embedding(t, dim, max_period=10000):
"""
Create sinusoidal timestep embeddings.
Args:
t (`torch.Tensor`): A 1-D Tensor of N indices, one per batch element.
These may be fractional.
dim (`int`): The dimension of the output.
max_period (`int`, optional): Controls the minimum frequency of the embeddings.
Returns:
`torch.Tensor`: An [N, D] Tensor of positional embeddings.
"""
half = dim // 2
freqs = torch.exp(
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
).to(t.device)
args = t[:, None].float() * freqs[None]
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
if dim % 2:
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
return embedding.to(t.dtype)
def forward(self, t):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
t_emb = self.mlp(t_freq)
return t_emb
class FeedForwardNetwork(nn.Module):
"""
Standard feed-forward network with SwiGLU activation.
Args:
embed_dim (`int`): Input dimension
ffn_dim (`int`): Hidden dimension
"""
def __init__(
self,
embed_dim,
ffn_dim,
):
super().__init__()
self.embed_dim = embed_dim
self.gate_proj = nn.Linear(self.embed_dim, ffn_dim, bias=False)
self.up_proj = nn.Linear(self.embed_dim, ffn_dim, bias=False)
self.down_proj = nn.Linear(ffn_dim, self.embed_dim, bias=False)
self.act_fn = ACT2FN['silu'] # Using SiLU as the activation function
def forward(self, x):
gate = self.gate_proj(x)
up = self.up_proj(x)
# SwiGLU activation
# gate = F.silu(gate)
gate = self.act_fn(gate)
return self.down_proj(gate * up)
class HeadLayer(nn.Module):
"""
A layer in the diffusion head.
Args:
embed_dim (`int`): Input dimension
ffn_dim (`int`): Hidden dimension
cond_dim (`int`): Condition embedding dimension
norm_eps (`float`, optional): Epsilon for normalization
"""
def __init__(
self,
embed_dim,
ffn_dim,
cond_dim,
norm_eps=1e-5,
):
super().__init__()
self.embed_dim = embed_dim
self.cond_dim = cond_dim
self.ffn_dim = ffn_dim
self.ffn = FeedForwardNetwork(
self.embed_dim,
self.ffn_dim,
)
self.norm = RMSNorm(self.embed_dim, eps=norm_eps)
self.adaLN_modulation = nn.Sequential(
# nn.SiLU(),
ACT2FN['silu'],
nn.Linear(cond_dim, 3 * self.embed_dim, bias=False)
)
def forward(self, x, c):
shift_ffn, scale_ffn, gate_ffn = self.adaLN_modulation(c).chunk(3, dim=-1)
x = x + gate_ffn * self.ffn(modulate(self.norm(x), shift_ffn, scale_ffn))
return x
class FinalLayer(nn.Module):
"""
Final layer in the diffusion head.
Args:
hidden_size (`int`): Input dimension
output_size (`int`): Output dimension
cond_size (`int`): Condition embedding dimension
norm_eps (`float`, optional): Epsilon for normalization
"""
def __init__(self, hidden_size, output_size, cond_size, norm_eps=1e-5):
super().__init__()
self.norm_final = RMSNorm(hidden_size, eps=norm_eps, elementwise_affine=False)
self.linear = nn.Linear(hidden_size, output_size, bias=False)
self.adaLN_modulation = nn.Sequential(
# nn.SiLU(),
ACT2FN['silu'],
nn.Linear(cond_size, 2 * hidden_size, bias=False)
)
def forward(self, x, c):
shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
x = modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
return x
class VibeVoiceDiffusionHead(PreTrainedModel):
"""
Diffusion head model for vibevoice.
Args:
config (`VibeVoiceDiffusionHeadConfig`): Model configuration
latent_size (`int`, optional): Size of the latent space. If not provided, uses `config.latent_size`.
"""
config_class = VibeVoiceDiffusionHeadConfig
supports_gradient_checkpointing = True
_supports_flash_attn_2 = True
_supports_sdpa = True
def __init__(
self,
config,
):
super().__init__(config)
self.config = config
self.cond_dim = config.hidden_size
latent_size = config.latent_size
self.noisy_images_proj = nn.Linear(latent_size, config.hidden_size, bias=False)
self.cond_proj = nn.Linear(config.hidden_size, self.cond_dim, bias=False)
self.t_embedder = TimestepEmbedder(self.cond_dim)
ffn_dim = int(config.hidden_size * config.head_ffn_ratio)
# Create the intermediate layers
self.layers = nn.ModuleList([
HeadLayer(
embed_dim=config.hidden_size,
ffn_dim=ffn_dim,
cond_dim=self.cond_dim,
norm_eps=config.rms_norm_eps
)
for _ in range(config.head_layers)
])
# Final layer for output
self.final_layer = FinalLayer(
hidden_size=config.hidden_size,
output_size=latent_size,
cond_size=self.cond_dim,
norm_eps=config.rms_norm_eps
)
self.initialize_weights()
def initialize_weights(self):
"""Initialize the weights of the model."""
# Initialize timestep embedder
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers
for layer in self.layers:
nn.init.constant_(layer.adaLN_modulation[-1].weight, 0)
# Zero-out output layers
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
nn.init.constant_(self.final_layer.linear.weight, 0)
def forward(
self,
noisy_images,
timesteps,
condition,
):
"""
Forward pass of the prediction head.
Args:
noisy_images (`torch.Tensor`): Noisy images/latents to denoise
timesteps (`torch.Tensor`): Timesteps for diffusion
condition (`torch.Tensor`): Conditioning information
Returns:
`torch.Tensor`: The predicted noise/velocity
"""
x = self.noisy_images_proj(noisy_images)
t = self.t_embedder(timesteps)
condition = self.cond_proj(condition)
c = condition + t
for layer in self.layers:
x = layer(x, c)
x = self.final_layer(x, c)
return x
AutoModel.register(VibeVoiceDiffusionHeadConfig, VibeVoiceDiffusionHead)
__all__ = [
"VibeVoiceDiffusionHead",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modular_vibevoice_diffusion_head.py",
"license": "MIT License",
"lines": 236,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/VibeVoice:vibevoice/modular/modular_vibevoice_text_tokenizer.py | """Tokenization classes for vibevoice."""
from typing import List, Optional, Union
from transformers.utils import logging
from transformers.models.qwen2.tokenization_qwen2 import Qwen2Tokenizer
from transformers.models.qwen2.tokenization_qwen2_fast import Qwen2TokenizerFast
logger = logging.get_logger(__name__)
class VibeVoiceTextTokenizer(Qwen2Tokenizer):
"""
Construct a VibeVoice tokenizer. Based on the Qwen2 tokenizer with additional special tokens for speech.
Args:
vocab_file (`str`):
Path to the vocabulary file.
merges_file (`str`):
Path to the merges file.
errors (`str`, *optional*, defaults to `"replace"`):
Paradigm to follow when decoding bytes to UTF-8.
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The unknown token.
bos_token (`str`, *optional*):
The beginning of sequence token. Not used for vibevoice.
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The end of sequence token.
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The token used for padding.
add_special_tokens (`bool`, *optional*, defaults to `True`):
Whether or not to add special tokens when encoding.
"""
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
vocab_file,
merges_file,
errors="replace",
unk_token="<|endoftext|>",
bos_token=None,
eos_token="<|endoftext|>",
pad_token="<|endoftext|>",
add_prefix_space=False,
add_special_tokens=True,
**kwargs,
):
super().__init__(
vocab_file=vocab_file,
merges_file=merges_file,
errors=errors,
unk_token=unk_token,
bos_token=bos_token,
eos_token=eos_token,
pad_token=pad_token,
add_prefix_space=add_prefix_space,
add_special_tokens=add_special_tokens,
**kwargs,
)
# Add VibeVoice-specific special tokens
self._add_vibevoice_special_tokens()
def _add_vibevoice_special_tokens(self):
"""Add VibeVoice-specific special tokens."""
special_tokens = {
"additional_special_tokens": [
"<|vision_start|>", # Speech start (reusing vision tokens)
"<|vision_end|>", # Speech end
"<|vision_pad|>", # Speech diffusion pad
]
}
num_added = self.add_special_tokens(special_tokens)
# Cache special token IDs
self._speech_start_id = self.convert_tokens_to_ids("<|vision_start|>")
self._speech_end_id = self.convert_tokens_to_ids("<|vision_end|>")
self._speech_diffusion_id = self.convert_tokens_to_ids("<|vision_pad|>")
self._eos_id = self.convert_tokens_to_ids('<|endoftext|>')
return num_added
@property
def eos_id(self) -> int:
"""Id of the end of sequence token."""
return self._eos_id
@property
def speech_start_id(self) -> int:
"""Id of the speech start token."""
return self._speech_start_id
@property
def speech_end_id(self) -> int:
"""Id of the speech end token."""
return self._speech_end_id
@property
def speech_diffusion_id(self) -> int:
"""Id of the speech diffusion token."""
return self._speech_diffusion_id
@property
def pad_id(self) -> int:
"""Id used for padding (returns -100 for loss masking)."""
return -100
class VibeVoiceTextTokenizerFast(Qwen2TokenizerFast):
"""
Construct a "fast" VibeVoice tokenizer (backed by HuggingFace's *tokenizers* library).
Based on the Qwen2 tokenizer with additional special tokens for speech.
Args:
vocab_file (`str`, *optional*):
Path to the vocabulary file.
merges_file (`str`, *optional*):
Path to the merges file.
tokenizer_file (`str`, *optional*):
Path to [tokenizers](https://github.com/huggingface/tokenizers) file.
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The unknown token.
bos_token (`str`, *optional*):
The beginning of sequence token. Not used for vibevoice.
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The end of sequence token.
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The token used for padding.
"""
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
vocab_file=None,
merges_file=None,
tokenizer_file=None,
unk_token="<|endoftext|>",
bos_token=None,
eos_token="<|endoftext|>",
pad_token="<|endoftext|>",
add_prefix_space=False,
**kwargs,
):
super().__init__(
vocab_file=vocab_file,
merges_file=merges_file,
tokenizer_file=tokenizer_file,
unk_token=unk_token,
bos_token=bos_token,
eos_token=eos_token,
pad_token=pad_token,
add_prefix_space=add_prefix_space,
**kwargs,
)
# Add VibeVoice-specific special tokens
self._add_vibevoice_special_tokens()
def _add_vibevoice_special_tokens(self):
"""Add VibeVoice-specific special tokens."""
special_tokens = {
"additional_special_tokens": [
"<|vision_start|>", # Speech start (reusing vision tokens)
"<|vision_end|>", # Speech end
"<|vision_pad|>", # Speech diffusion pad
]
}
num_added = self.add_special_tokens(special_tokens)
# Cache special token IDs
self._speech_start_id = self.convert_tokens_to_ids("<|vision_start|>")
self._speech_end_id = self.convert_tokens_to_ids("<|vision_end|>")
self._speech_diffusion_id = self.convert_tokens_to_ids("<|vision_pad|>")
# self._eos_id = self.convert_tokens_to_ids('<|endoftext|>')
self._eos_id = self.eos_token_id # qwen2 / qwen3
self._pad_id = self.convert_tokens_to_ids('<|image_pad|>')
return num_added
@property
def eos_id(self) -> int:
"""Id of the end of sequence token."""
return self._eos_id
@property
def speech_start_id(self) -> int:
"""Id of the speech start token."""
return self._speech_start_id
@property
def speech_end_id(self) -> int:
"""Id of the speech end token."""
return self._speech_end_id
@property
def speech_diffusion_id(self) -> int:
"""Id of the speech diffusion token."""
return self._speech_diffusion_id
@property
def pad_id(self) -> int:
"""Id used for padding (returns -100 for loss masking)."""
return self._pad_id
class VibeVoiceASRTextTokenizerFast(Qwen2TokenizerFast):
"""
Construct a "fast" VibeVoice tokenizer (backed by HuggingFace's *tokenizers* library).
Based on the Qwen2 tokenizer with additional special tokens for speech.
Args:
vocab_file (`str`, *optional*):
Path to the vocabulary file.
merges_file (`str`, *optional*):
Path to the merges file.
tokenizer_file (`str`, *optional*):
Path to [tokenizers](https://github.com/huggingface/tokenizers) file.
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The unknown token.
bos_token (`str`, *optional*):
The beginning of sequence token. Not used for vibevoice.
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The end of sequence token.
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The token used for padding.
"""
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
vocab_file=None,
merges_file=None,
tokenizer_file=None,
unk_token="<|endoftext|>",
bos_token=None,
eos_token="<|endoftext|>",
pad_token="<|endoftext|>",
add_prefix_space=False,
**kwargs,
):
super().__init__(
vocab_file=vocab_file,
merges_file=merges_file,
tokenizer_file=tokenizer_file,
unk_token=unk_token,
bos_token=bos_token,
eos_token=eos_token,
pad_token=pad_token,
add_prefix_space=add_prefix_space,
**kwargs,
)
# Add VibeVoice-specific special tokens
self._add_vibevoice_special_tokens()
# https://github.com/QwenLM/Qwen2.5-VL/blob/d2240f11656bfe404b9ba56db4e51cd09f522ff1/qwen-vl-finetune/qwenvl/data/data_qwen_packed.py#L57C5-L57C222
self.chat_template = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
def _add_vibevoice_special_tokens(self):
"""Add VibeVoice-specific special tokens."""
special_tokens = {
"additional_special_tokens": [
"<|object_ref_start|>", # Speech start (reusing vision tokens)
"<|object_ref_end|>", # Speech end
"<|box_start|>", # Speech diffusion pad
]
}
num_added = self.add_special_tokens(special_tokens)
# Cache special token IDs
self._speech_start_id = self.convert_tokens_to_ids("<|object_ref_start|>")
self._speech_end_id = self.convert_tokens_to_ids("<|object_ref_end|>")
self._speech_pad_id = self.convert_tokens_to_ids("<|box_start|>")
self._eos_id = self.eos_token_id # qwen2 / qwen3
self._pad_id = self.convert_tokens_to_ids('<|image_pad|>')
return num_added
@property
def eos_id(self) -> int:
"""Id of the end of sequence token."""
return self._eos_id
@property
def speech_start_id(self) -> int:
"""Id of the speech start token."""
return self._speech_start_id
@property
def speech_end_id(self) -> int:
"""Id of the speech end token."""
return self._speech_end_id
@property
def speech_pad_id(self) -> int:
"""Id of the speech diffusion token."""
return self._speech_pad_id
@property
def pad_id(self) -> int:
return self._pad_id
__all__ = [
"VibeVoiceTextTokenizer",
"VibeVoiceTextTokenizerFast",
"VibeVoiceASRTextTokenizerFast",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modular_vibevoice_text_tokenizer.py",
"license": "MIT License",
"lines": 264,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/modular_vibevoice_tokenizer.py | import math
import typing as tp
from functools import partial
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple, Union
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.auto import AutoModel
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
from transformers.modeling_utils import PreTrainedModel
from transformers.activations import ACT2FN
from .configuration_vibevoice import VibeVoiceAcousticTokenizerConfig, VibeVoiceSemanticTokenizerConfig
logger = logging.get_logger(__name__)
import os
# Try to import APEX FusedRMSNorm
try:
from apex.normalization.fused_layer_norm import fused_rms_norm_affine
APEX_AVAILABLE = True
# logger.info("APEX FusedRMSNorm is available and will be used for optimization")
if int(os.getenv("OPTIMIZE_FOR_SPEED", "0")) == 0:
APEX_AVAILABLE = False
# logger.warning("APEX FusedRMSNorm is disabled by environment variable OPTIMIZE_FOR_SPEED=0")
except ImportError:
APEX_AVAILABLE = False
# logger.warning("APEX FusedRMSNorm not available, using native implementation")
# Normalization modules
class ConvLayerNorm(nn.LayerNorm):
"""
Convolution-friendly LayerNorm that moves channels to last dimensions
before running the normalization and moves them back to original position right after.
"""
def __init__(self, normalized_shape: tp.Union[int, tp.List[int], torch.Size], **kwargs):
super().__init__(normalized_shape, **kwargs)
def forward(self, x):
x = x.transpose(1, 2) # b ... t -> b t ...
x = nn.functional.layer_norm(x.float(), self.normalized_shape, self.weight.float(), self.bias.float(), self.eps).type_as(x)
x = x.transpose(1, 2) # b t ... -> b ... t
return x
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-5, elementwise_affine=True, weight_shape=None):
super().__init__()
self.dim = dim
self.eps = eps
self.elementwise_affine = elementwise_affine
if self.elementwise_affine:
weight_shape = (dim,) if weight_shape is None else weight_shape
self.weight = nn.Parameter(torch.ones(weight_shape))
else:
self.register_parameter('weight', None)
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float()).type_as(x)
if self.weight is not None:
output = output * self.weight
return output
def extra_repr(self) -> str:
return f'dim={self.dim}, eps={self.eps}, elementwise_affine={self.elementwise_affine}'
class ConvRMSNorm(RMSNorm):
def __init__(self, dim: int, eps: float = 1e-5, elementwise_affine=True, weight_shape=None):
super().__init__(dim, eps, elementwise_affine, weight_shape)
def forward(self, x):
x = x.transpose(1, 2) # b ... t -> b t ...
if (not APEX_AVAILABLE) or (not self.elementwise_affine):
# Fallback to native implementation
output = self._norm(x.float()).type_as(x)
if self.weight is not None:
output = output * self.weight
else:
output = fused_rms_norm_affine(x, self.weight, self.weight.shape, self.eps)
output = output.transpose(1, 2) # b t ... -> b ... t
return output
# Convolutional layers and utilities
CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm',
'time_layer_norm', 'layer_norm', 'time_group_norm'])
def apply_parametrization_norm(module: nn.Module, norm: str = 'none') -> nn.Module:
assert norm in CONV_NORMALIZATIONS
if norm == 'weight_norm':
return nn.utils.weight_norm(module)
elif norm == 'spectral_norm':
return nn.utils.spectral_norm(module)
else:
# We already check was in CONV_NORMALIZATION, so any other choice
# doesn't need reparametrization.
return module
def get_norm_module(module: nn.Module, causal: bool = False, norm: str = 'none', **norm_kwargs) -> nn.Module:
"""Return the proper normalization module. If causal is True, this will ensure the returned
module is causal, or return an error if the normalization doesn't support causal evaluation.
"""
assert norm in CONV_NORMALIZATIONS
if norm == 'layer_norm':
assert isinstance(module, nn.modules.conv._ConvNd)
return ConvLayerNorm(module.out_channels, **norm_kwargs)
elif norm == 'time_group_norm':
if causal:
raise ValueError("GroupNorm doesn't support causal evaluation.")
assert isinstance(module, nn.modules.conv._ConvNd)
return nn.GroupNorm(1, module.out_channels, **norm_kwargs)
else:
return nn.Identity()
def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
padding_total: int = 0) -> int:
"""Calculate extra padding needed for convolution to have the same output length"""
length = x.shape[-1]
n_frames = (length - kernel_size + padding_total) / stride + 1
ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
return ideal_length - length
def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'zero', value: float = 0.):
"""Pad 1D input with handling for small inputs in reflect mode"""
length = x.shape[-1]
padding_left, padding_right = paddings
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
if mode == 'reflect':
max_pad = max(padding_left, padding_right)
extra_pad = 0
if length <= max_pad:
extra_pad = max_pad - length + 1
x = F.pad(x, (0, extra_pad))
padded = F.pad(x, paddings, mode, value)
end = padded.shape[-1] - extra_pad
return padded[..., :end]
else:
return F.pad(x, paddings, mode, value)
def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
"""Remove padding from x, handling properly zero padding. Only for 1d!"""
padding_left, padding_right = paddings
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
assert (padding_left + padding_right) <= x.shape[-1]
end = x.shape[-1] - padding_right
return x[..., padding_left: end]
class NormConv1d(nn.Module):
"""Wrapper around Conv1d and normalization applied to this conv"""
def __init__(self, *args, causal: bool = False, norm: str = 'none',
norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
super().__init__()
self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm)
self.norm = get_norm_module(self.conv, causal, norm, **norm_kwargs)
self.norm_type = norm
def forward(self, x):
x = self.conv(x)
x = self.norm(x)
return x
class NormConvTranspose1d(nn.Module):
"""Wrapper around ConvTranspose1d and normalization applied to this conv"""
def __init__(self, *args, causal: bool = False, norm: str = 'none',
norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
super().__init__()
self.convtr = apply_parametrization_norm(nn.ConvTranspose1d(*args, **kwargs), norm)
self.norm = get_norm_module(self.convtr, causal, norm, **norm_kwargs)
self.norm_type = norm
def forward(self, x):
x = self.convtr(x)
x = self.norm(x)
return x
class VibeVoiceTokenizerStreamingCache:
"""Cache for streaming convolution, similar to KV cache in attention"""
def __init__(self):
self.cache = {} # Dict mapping (layer_id, sample_idx) to state tensor
def get(self, layer_id: str, sample_indices: torch.Tensor) -> Optional[torch.Tensor]:
"""Get cached states for given layer and sample indices"""
states = []
max_length = 0
# First pass: collect states and find max length
for idx in sample_indices.tolist():
key = (layer_id, idx)
if key not in self.cache:
return None # If any sample is missing, return None
state = self.cache[key]
states.append(state)
max_length = max(max_length, state.shape[-1])
# Second pass: pad states to max length if needed
if len(states) > 0 and states[0].dim() >= 2:
padded_states = []
for state in states:
if state.shape[-1] < max_length:
# Pad on the time dimension (last dimension)
pad_size = max_length - state.shape[-1]
# Pad with zeros on the LEFT to align the most recent samples
padded_state = F.pad(state, (pad_size, 0), mode='constant', value=0)
padded_states.append(padded_state)
else:
padded_states.append(state)
return torch.stack(padded_states, dim=0)
else:
return torch.stack(states, dim=0)
def set(self, layer_id: str, sample_indices: torch.Tensor, states: torch.Tensor):
"""Set cached states for given layer and sample indices"""
for i, idx in enumerate(sample_indices.tolist()):
key = (layer_id, idx)
self.cache[key] = states[i].detach()
def set_to_zero(self, sample_indices: torch.Tensor):
"""Set all cached states to zero for given sample indices"""
for key in list(self.cache.keys()):
layer_id, sample_idx = key
if sample_idx in sample_indices.tolist():
# Create zero tensor with same shape and dtype as cached tensor
cached_tensor = self.cache[key]
self.cache[key] = torch.zeros_like(cached_tensor)
def clear(self, layer_id: Optional[str] = None, sample_indices: Optional[torch.Tensor] = None):
"""Clear cache for specific layer/samples or everything"""
if layer_id is None and sample_indices is None:
self.cache.clear()
elif layer_id is not None and sample_indices is None:
# Clear all samples for a specific layer
keys_to_remove = [k for k in self.cache.keys() if k[0] == layer_id]
for k in keys_to_remove:
del self.cache[k]
elif layer_id is not None and sample_indices is not None:
# Clear specific samples for a specific layer
for idx in sample_indices.tolist():
key = (layer_id, idx)
self.cache.pop(key, None)
class SConv1d(nn.Module):
"""Conv1d with built-in handling of asymmetric or causal padding and normalization."""
def __init__(self, in_channels: int, out_channels: int,
kernel_size: int, stride: int = 1, dilation: int = 1,
groups: int = 1, bias: bool = True, causal: bool = False,
norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {},
pad_mode: str = 'reflect'):
super().__init__()
self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride,
dilation=dilation, groups=groups, bias=bias, causal=causal,
norm=norm, norm_kwargs=norm_kwargs)
self.causal = causal
self.pad_mode = pad_mode
# Store configuration
self.kernel_size = kernel_size
self.dilation = dilation
self.stride = stride
self.in_channels = in_channels
self.out_channels = out_channels
# For causal convolution, we need to maintain kernel_size - 1 samples as context
# need to check use which context_size is more suitable
# self.context_size = (kernel_size - 1) * dilation
self.context_size = (kernel_size - 1) * dilation - (stride - 1)
# For non-streaming mode, calculate padding
self.padding_total = (kernel_size - 1) * dilation - (stride - 1)
# Create a unique layer ID for cache management
self._layer_id = None
@property
def layer_id(self):
if self._layer_id is None:
self._layer_id = f"sconv1d_{id(self)}"
return self._layer_id
def forward(self, x: torch.Tensor,
cache: Optional[VibeVoiceTokenizerStreamingCache] = None,
sample_indices: Optional[torch.Tensor] = None,
use_cache: bool = False,
debug: bool = False,
is_final_chunk: bool = False) -> torch.Tensor:
"""
Forward pass with optional streaming support via cache.
Args:
x: Input tensor [batch_size, channels, time]
cache: VibeVoiceTokenizerStreamingCache object for maintaining states
sample_indices: Indices identifying each sample for cache management
use_cache: Whether to use cached states for streaming
debug: Whether to print debug information
is_final_chunk: Whether this is the final chunk (adds extra padding for alignment)
Returns:
Output tensor
"""
B, C, T = x.shape
# Non-streaming mode
if not use_cache or cache is None:
return self._forward_non_streaming(x, debug=debug)
# Streaming mode
assert self.causal, "Streaming mode is only supported for causal convolutions"
assert sample_indices is not None, "sample_indices must be provided for streaming mode"
assert len(sample_indices) == B, "sample_indices must match batch size"
return self._forward_streaming(x, cache, sample_indices, debug, is_final_chunk)
def _forward_streaming(self, x: torch.Tensor,
cache: VibeVoiceTokenizerStreamingCache,
sample_indices: torch.Tensor,
debug: bool = False,
is_final_chunk: bool = False) -> torch.Tensor:
"""Streaming forward pass with cache operations kept separate from compiled code"""
B, C, T = x.shape
# Cache operations (not compiled)
cached_states = cache.get(self.layer_id, sample_indices)
if cached_states is None:
# First chunk - initialize with zeros for context
if self.context_size > 0:
cached_states = torch.zeros(B, C, self.context_size, device=x.device, dtype=x.dtype)
if debug:
print(f"[DEBUG] Initialized cache with shape: {cached_states.shape}, context_size={self.context_size}")
else:
cached_states = torch.zeros(B, C, 0, device=x.device, dtype=x.dtype)
if debug:
print(f"[DEBUG] No context needed (kernel_size=stride)")
# Concatenate cached states with input
if cached_states.shape[2] > 0:
input_with_context = torch.cat([cached_states, x], dim=2)
else:
input_with_context = x
# For final chunk, add extra padding to ensure ceil behavior (same as non-streaming)
if is_final_chunk:
extra_padding = get_extra_padding_for_conv1d(
input_with_context, self.kernel_size, self.stride, self.padding_total
)
if extra_padding > 0:
input_with_context = pad1d(input_with_context, (0, extra_padding), mode=self.pad_mode)
if debug:
print(f"[DEBUG] Final chunk: added extra_padding={extra_padding}")
if debug:
print(f"[DEBUG] Input shape: {x.shape}, Cache shape: {cached_states.shape}, Combined: {input_with_context.shape}")
# Apply convolution directly - no extra padding in streaming mode
# The conv layer will handle its own padding internally
output = self.conv(input_with_context)
if debug:
print(f"[DEBUG] Output shape: {output.shape}")
# Update cache for next chunk
if self.context_size > 0:
# Calculate how many samples to keep
total_input_length = input_with_context.shape[2]
# Keep the last context_size samples
if total_input_length >= self.context_size:
new_cache_start = total_input_length - self.context_size
new_cache = input_with_context[:, :, new_cache_start:]
else:
# If we have less than context_size samples, keep everything
new_cache = input_with_context
if debug:
print(f"[DEBUG] New cache shape: {new_cache.shape}")
cache.set(self.layer_id, sample_indices, new_cache)
return output
def _forward_non_streaming(self, x: torch.Tensor, debug: bool = False) -> torch.Tensor:
"""Standard forward pass without streaming"""
B, C, T = x.shape
kernel_size = self.kernel_size
stride = self.stride
dilation = self.dilation
padding_total = self.padding_total
# Compute extra padding for stride alignment
extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
if debug:
print(f"[DEBUG NON-STREAMING] Input shape: {x.shape}, padding_total={padding_total}, extra_padding={extra_padding}")
if self.causal:
# Left padding for causal
if self.pad_mode == 'constant':
x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode, value=0)
else:
x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode)
else:
# Symmetric padding for non-causal
padding_right = padding_total // 2
padding_left = padding_total - padding_right
x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode)
if debug:
print(f"[DEBUG NON-STREAMING] After padding: {x.shape}")
output = self.conv(x)
if debug:
print(f"[DEBUG NON-STREAMING] Output shape: {output.shape}")
return output
class SConvTranspose1d(nn.Module):
"""ConvTranspose1d with built-in handling of asymmetric or causal padding and normalization."""
def __init__(self, in_channels: int, out_channels: int,
kernel_size: int, stride: int = 1, causal: bool = False,
norm: str = 'none', trim_right_ratio: float = 1.,
norm_kwargs: tp.Dict[str, tp.Any] = {}, bias: bool = True):
super().__init__()
self.convtr = NormConvTranspose1d(in_channels, out_channels, kernel_size, stride,
causal=causal, norm=norm, norm_kwargs=norm_kwargs, bias=bias)
self.causal = causal
self.trim_right_ratio = trim_right_ratio
assert self.causal or self.trim_right_ratio == 1., \
"`trim_right_ratio` != 1.0 only makes sense for causal convolutions"
assert self.trim_right_ratio >= 0. and self.trim_right_ratio <= 1.
# Store configuration
self.kernel_size = kernel_size
self.stride = stride
self.in_channels = in_channels
self.out_channels = out_channels
# For transposed convolution, padding calculation is different
self.padding_total = kernel_size - stride
# For streaming, we need to keep track of input history
# Transposed conv needs to see multiple input samples to produce correct output
self.context_size = kernel_size - 1
# Create a unique layer ID for cache management
self._layer_id = None
@property
def layer_id(self):
if self._layer_id is None:
self._layer_id = f"sconvtr1d_{id(self)}"
return self._layer_id
def forward(self, x: torch.Tensor,
cache: Optional[VibeVoiceTokenizerStreamingCache] = None,
sample_indices: Optional[torch.Tensor] = None,
use_cache: bool = False,
debug: bool = False) -> torch.Tensor:
"""
Forward pass with optional streaming support via cache.
"""
B, C, T = x.shape
# Non-streaming mode
if not use_cache or cache is None:
return self._forward_non_streaming(x, debug=debug)
# Streaming mode
assert sample_indices is not None, "sample_indices must be provided for streaming mode"
assert len(sample_indices) == B, "sample_indices must match batch size"
return self._forward_streaming(x, cache, sample_indices, debug)
def _forward_streaming(self, x: torch.Tensor,
cache: VibeVoiceTokenizerStreamingCache,
sample_indices: torch.Tensor,
debug: bool = False) -> torch.Tensor:
"""Streaming forward pass with cache operations kept separate from compiled code"""
B, C, T = x.shape
# Cache operations (not compiled)
cached_input = cache.get(self.layer_id, sample_indices)
if cached_input is None:
# First chunk - no history yet
cached_input = torch.zeros(B, C, 0, device=x.device, dtype=x.dtype)
if debug:
print(f"[DEBUG] Initialized empty cache for transposed conv")
# Concatenate cached input with new input
full_input = torch.cat([cached_input, x], dim=2)
if debug:
print(f"[DEBUG] Input shape: {x.shape}, Cache shape: {cached_input.shape}, Combined: {full_input.shape}")
# First chunk or debug mode - use uncompiled version
full_output = self.convtr(full_input)
if debug:
print(f"[DEBUG] Full transposed conv output shape: {full_output.shape}")
# Calculate padding to remove
if self.causal:
padding_right = math.ceil(self.padding_total * self.trim_right_ratio)
padding_left = self.padding_total - padding_right
else:
padding_right = self.padding_total // 2
padding_left = self.padding_total - padding_right
# Remove padding
if padding_left + padding_right > 0:
full_output = unpad1d(full_output, (padding_left, padding_right))
if debug:
print(f"[DEBUG] After unpadding: {full_output.shape}")
# Determine which part of the output corresponds to the new input
if cached_input.shape[2] == 0:
# First chunk - return all output
output = full_output
else:
# Subsequent chunks - return only the new output
expected_new_output = T * self.stride
# Take the last expected_new_output samples
if full_output.shape[2] >= expected_new_output:
output = full_output[:, :, -expected_new_output:]
else:
output = full_output
if debug:
print(f"[DEBUG] Final streaming output shape: {output.shape}")
# Update cache
if full_input.shape[2] > self.context_size:
new_cache = full_input[:, :, -self.context_size:]
else:
new_cache = full_input
if debug:
print(f"[DEBUG] New cache shape: {new_cache.shape}")
cache.set(self.layer_id, sample_indices, new_cache)
return output
def _forward_non_streaming(self, x: torch.Tensor, debug: bool = False) -> torch.Tensor:
"""Standard forward pass without streaming"""
if debug:
print(f"[DEBUG NON-STREAMING] Input shape: {x.shape}")
# Apply transposed convolution
y = self.convtr(x)
if debug:
print(f"[DEBUG NON-STREAMING] After transposed conv: {y.shape}")
# Calculate and remove padding
if self.causal:
padding_right = math.ceil(self.padding_total * self.trim_right_ratio)
padding_left = self.padding_total - padding_right
else:
padding_right = self.padding_total // 2
padding_left = self.padding_total - padding_right
if padding_left + padding_right > 0:
y = unpad1d(y, (padding_left, padding_right))
if debug:
print(f"[DEBUG NON-STREAMING] Final output shape: {y.shape}")
return y
# FFN
class FFN(nn.Module):
def __init__(
self,
embed_dim,
ffn_dim,
bias=False,
):
super().__init__()
self.embed_dim = embed_dim
self.linear1 = nn.Linear(self.embed_dim, ffn_dim, bias=bias)
self.gelu = ACT2FN["gelu"]
self.linear2 = nn.Linear(ffn_dim, self.embed_dim, bias=bias)
def forward(self, x):
x = self.linear1(x)
x = self.gelu(x)
x = self.linear2(x)
return x
class Convlayer(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
dilation=1,
groups=1,
bias=True,
pad_mode='zeros',
norm='weight_norm',
causal=True,
):
super().__init__()
self.conv = SConv1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation,
groups=groups, bias=bias, pad_mode=pad_mode, norm=norm, causal=causal)
def forward(self, x):
return self.conv(x)
class Block1D(nn.Module):
def __init__(self, dim, kernel_size=7, drop_path=0., mixer_layer='conv',
layer_scale_init_value=1e-6, **kwargs):
super().__init__()
if kwargs.get('layernorm', 'LN') == 'LN':
self.norm = ConvLayerNorm(dim, eps=kwargs.get('eps', 1e-6))
self.ffn_norm = ConvLayerNorm(dim, eps=kwargs.get('eps', 1e-6))
elif kwargs.get('layernorm', 'RMSNorm') == 'RMSNorm':
self.norm = ConvRMSNorm(dim, eps=kwargs.get('eps', 1e-6))
self.ffn_norm = ConvRMSNorm(dim, eps=kwargs.get('eps', 1e-6))
if mixer_layer == 'conv':
self.mixer = Convlayer(dim, dim, groups=kwargs.get('groups', 1),
kernel_size=kernel_size,
pad_mode=kwargs.get('pad_mode', 'reflect'),
norm=kwargs.get('norm', 'none'),
causal=kwargs.get('causal', True),
bias=kwargs.get('bias', True),
)
elif mixer_layer == 'depthwise_conv':
self.mixer = Convlayer(dim, dim, groups=dim,
kernel_size=kernel_size,
pad_mode=kwargs.get('pad_mode', 'reflect'),
norm=kwargs.get('norm', 'none'),
causal=kwargs.get('causal', True),
bias=kwargs.get('bias', True),
)
else:
raise ValueError(f"Unsupported mixer layer: {mixer_layer}")
self.ffn = FFN(
dim,
kwargs.get('ffn_expansion', 4) * dim,
bias=kwargs.get('bias', False),
)
self.drop_path = nn.Identity() if drop_path <= 0. else nn.modules.DropPath(drop_path)
if layer_scale_init_value > 0:
self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
self.ffn_gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
else:
self.gamma = None
self.ffn_gamma = None
def forward(self, x):
# mixer
residual = x
x = self.norm(x)
x = self.mixer(x)
if self.gamma is not None:
x = x * self.gamma.unsqueeze(-1)
x = residual + self.drop_path(x)
# ffn
residual = x
x = self.ffn_norm(x)
x = x.permute(0, 2, 1)
x = self.ffn(x)
x = x.permute(0, 2, 1)
if self.ffn_gamma is not None:
x = x * self.ffn_gamma.unsqueeze(-1)
x = residual + self.drop_path(x)
return x
class TokenizerEncoder(nn.Module):
"""
Encoder component for the VibeVoice tokenizer that converts audio to latent representations.
Args:
config: Configuration object with model parameters
"""
def __init__(self, config):
super().__init__()
# Extract parameters from config
self.channels = config.channels
self.dimension = config.dimension
self.n_filters = config.n_filters
self.ratios = list(reversed(config.ratios))
self.depths = config.depths
self.n_residual_layers = getattr(config, "n_residual_layers", 1)
self.hop_length = np.prod(self.ratios)
self.causal = config.causal
# Additional config parameters with defaults
kernel_size = getattr(config, "kernel_size", 7)
last_kernel_size = getattr(config, "last_kernel_size", 7)
norm = getattr(config, "norm", "none")
norm_params = getattr(config, "norm_params", {})
pad_mode = getattr(config, "pad_mode", "reflect")
bias = getattr(config, "bias", True)
layernorm = getattr(config, "layernorm", "LN")
layernorm_eps = getattr(config, "layernorm_eps", 1e-6)
layernorm_elementwise_affine = getattr(config, "layernorm_elementwise_affine", True)
drop_path_rate = getattr(config, "drop_path_rate", 0.0)
mixer_layer = getattr(config, "mixer_layer", "conv")
layer_scale_init_value = getattr(config, "layer_scale_init_value", 0)
disable_last_norm = getattr(config, "disable_last_norm", False)
# determine the norm type based on layernorm
if layernorm == 'LN':
norm_type = ConvLayerNorm
elif layernorm == 'RMSNorm':
norm_type = partial(ConvRMSNorm, elementwise_affine=layernorm_elementwise_affine)
else:
raise ValueError(f"Unsupported norm type: {layernorm}")
# stem and intermediate downsampling conv layers
stem = nn.Sequential(
SConv1d(self.channels, self.n_filters, kernel_size, norm=norm, norm_kwargs=norm_params, causal=self.causal, pad_mode=pad_mode, bias=bias),
)
self.downsample_layers = nn.ModuleList()
self.downsample_layers.append(stem)
for i in range(len(self.ratios)):
in_ch = self.n_filters * (2 ** i)
out_ch = self.n_filters * (2 ** (i + 1))
downsample_layer = nn.Sequential(
SConv1d(in_ch, out_ch, kernel_size=self.ratios[i] * 2, stride=self.ratios[i], causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
)
self.downsample_layers.append(downsample_layer)
# configure the transformer blocks
layer_type = partial(
Block1D,
mixer_layer=mixer_layer,
layernorm=layernorm,
eps=layernorm_eps,
causal=self.causal,
pad_mode=pad_mode,
norm=norm,
bias=bias,
layer_scale_init_value=layer_scale_init_value,
)
self.stages = nn.ModuleList()
dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
cur = 0
for i in range(len(self.depths)):
in_ch = self.n_filters * (2 ** i)
stage = nn.Sequential(
*[layer_type(dim=in_ch, drop_path=dp_rates[cur + j]) for j in range(self.depths[i])]
)
self.stages.append(stage)
cur += self.depths[i]
if not disable_last_norm:
self.norm = norm_type(in_ch, eps=layernorm_eps)
else:
self.norm = nn.Identity()
self.head = SConv1d(in_ch, self.dimension, kernel_size=last_kernel_size, causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
def forward_features(self, x, cache=None, sample_indices=None, use_cache=False, debug=False, is_final_chunk=False):
for i in range(len(self.depths)):
# Apply downsampling
for layer in self.downsample_layers[i]:
if isinstance(layer, SConv1d):
x = layer(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
else:
x = layer(x)
# Apply stage (Block1D contains Convlayer which contains SConv1d)
for block in self.stages[i]:
if hasattr(block, 'mixer') and hasattr(block.mixer, 'conv') and isinstance(block.mixer.conv, SConv1d):
# Block1D forward with cache support
residual = x
x = block.norm(x)
x = block.mixer.conv(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
if block.gamma is not None:
x = x * block.gamma.unsqueeze(-1)
x = residual + x
# FFN part
residual = x
x = block.ffn_norm(x)
x = x.permute(0, 2, 1)
x = block.ffn(x)
x = x.permute(0, 2, 1)
if block.ffn_gamma is not None:
x = x * block.ffn_gamma.unsqueeze(-1)
x = residual + x
else:
x = block(x)
return self.norm(x)
def forward(self, x, cache=None, sample_indices=None, use_cache=False, debug=False, is_final_chunk=False):
x = self.forward_features(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
x = self.head(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
return x
class TokenizerDecoder(nn.Module):
"""
Decoder component for the VibeVoice tokenizer that converts latent representations back to audio.
Args:
config: Configuration object with model parameters
"""
def __init__(self, config):
super().__init__()
# Extract parameters from config
self.dimension = config.dimension
self.channels = config.channels
self.n_filters = config.n_filters
self.ratios = config.ratios
# IMPORTANT CHANGE: Don't reverse depths again since they're already reversed in VibeVoiceAcousticTokenizerModel
self.depths = config.depths # Changed from list(reversed(config.depths))
self.n_residual_layers = getattr(config, "n_residual_layers", 1)
self.hop_length = np.prod(self.ratios)
self.causal = config.causal
# Additional config parameters with defaults
kernel_size = getattr(config, "kernel_size", 7)
last_kernel_size = getattr(config, "last_kernel_size", 7)
norm = getattr(config, "norm", "none")
norm_params = getattr(config, "norm_params", {})
pad_mode = getattr(config, "pad_mode", "reflect")
bias = getattr(config, "bias", True)
layernorm = getattr(config, "layernorm", "LN")
layernorm_eps = getattr(config, "layernorm_eps", 1e-6)
trim_right_ratio = getattr(config, "trim_right_ratio", 1.0)
layernorm_elementwise_affine = getattr(config, "layernorm_elementwise_affine", True)
drop_path_rate = getattr(config, "drop_path_rate", 0.0)
mixer_layer = getattr(config, "mixer_layer", "conv")
layer_scale_init_value = getattr(config, "layer_scale_init_value", 0)
disable_last_norm = getattr(config, "disable_last_norm", False)
# determine the norm type based on layernorm
if layernorm == 'LN':
norm_type = ConvLayerNorm
elif layernorm == 'RMSNorm':
norm_type = partial(ConvRMSNorm, elementwise_affine=layernorm_elementwise_affine)
else:
raise ValueError(f"Unsupported norm type: {layernorm}")
# stem and upsampling layers
stem = nn.Sequential(
SConv1d(self.dimension, self.n_filters * 2 ** (len(self.depths) - 1), kernel_size, norm=norm,
norm_kwargs=norm_params, causal=self.causal, pad_mode=pad_mode, bias=bias),
)
self.upsample_layers = nn.ModuleList()
self.upsample_layers.append(stem)
for i in range(len(self.ratios)):
in_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i))
out_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i - 1))
upsample_layer = nn.Sequential(
SConvTranspose1d(in_ch, out_ch,
kernel_size=self.ratios[i] * 2, stride=self.ratios[i],
norm=norm, norm_kwargs=norm_params, bias=bias,
causal=self.causal, trim_right_ratio=trim_right_ratio),
)
self.upsample_layers.append(upsample_layer)
# configure transformer blocks
layer_type = partial(
Block1D,
mixer_layer=mixer_layer,
layernorm=layernorm,
eps=layernorm_eps,
causal=self.causal,
pad_mode=pad_mode,
norm=norm,
bias=bias,
layer_scale_init_value=layer_scale_init_value,
)
self.stages = nn.ModuleList()
dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
cur = 0
# Create stages in the same order as the original model
for i in range(len(self.depths)):
in_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i))
stage = nn.Sequential(
*[layer_type(dim=in_ch, drop_path=dp_rates[cur + j]) for j in range(self.depths[i])]
)
self.stages.append(stage)
cur += self.depths[i]
if not disable_last_norm:
self.norm = norm_type(in_ch, eps=layernorm_eps)
else:
self.norm = nn.Identity()
self.head = SConv1d(in_ch, self.channels, kernel_size=last_kernel_size, causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
def forward_features(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
for i in range(len(self.depths)):
# Apply upsampling
for layer in self.upsample_layers[i]:
if isinstance(layer, (SConv1d, SConvTranspose1d)):
x = layer(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
else:
x = layer(x)
# Apply stage (Block1D contains Convlayer which contains SConv1d)
for block in self.stages[i]:
if hasattr(block, 'mixer') and hasattr(block.mixer, 'conv') and isinstance(block.mixer.conv, SConv1d):
# Block1D forward with cache support
residual = x
x = block.norm(x)
x = block.mixer.conv(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
if block.gamma is not None:
x = x * block.gamma.unsqueeze(-1)
x = residual + x
# FFN part
residual = x
x = block.ffn_norm(x)
x = x.permute(0, 2, 1)
x = block.ffn(x)
x = x.permute(0, 2, 1)
if block.ffn_gamma is not None:
x = x * block.ffn_gamma.unsqueeze(-1)
x = residual + x
else:
x = block(x)
return self.norm(x)
def forward(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
x = self.forward_features(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
x = self.head(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
return x
@dataclass
class VibeVoiceTokenizerEncoderOutput:
"""
Output of VibeVoice tokenizer encoder, representing a Gaussian distribution with fixed variance.
Args:
mean (`torch.FloatTensor`): The mean parameters of the distribution.
std (`float` or `torch.FloatTensor`): Fixed standard deviation value.
"""
mean: torch.Tensor
std: Optional[Union[float, torch.Tensor]] = None
def sample(self, dist_type='fix'):
"""
Sample from the distribution.
Args:
dist_type (`str`): Sampling method, either 'fix' or 'gaussian'.
Returns:
`torch.FloatTensor`: Sampled values.
`torch.FloatTensor` (optional): Standard deviation used (only when dist_type='gaussian').
"""
if dist_type == 'fix':
x = self.mean + self.std * torch.randn_like(self.mean)
return x, self.std
elif dist_type == 'gaussian':
batch_size = self.mean.size(0)
value = self.std / 0.8
std = torch.randn(batch_size, device=self.mean.device, dtype=self.mean.dtype) * value
while std.dim() < self.mean.dim():
std = std.unsqueeze(-1)
x = self.mean + std * torch.randn_like(self.mean)
return x, std
else:
return self.mean, self.std
def kl(self):
"""Compute KL divergence between this distribution and a standard normal."""
target = torch.zeros_like(self.mean)
return F.mse_loss(self.mean, target, reduction='none')
def mode(self):
"""Return the distribution mode (which is the mean for Gaussian)."""
return self.mean
class VibeVoiceAcousticTokenizerModel(PreTrainedModel):
"""VibeVoice speech tokenizer model combining encoder and decoder for acoustic tokens"""
config_class = VibeVoiceAcousticTokenizerConfig
base_model_prefix = "vibevoice_acoustic_tokenizer"
_supports_flash_attn_2 = True
_supports_sdpa = True
_no_split_modules = ["TokenizerEncoder", "TokenizerDecoder"]
def __init__(self, config):
super().__init__(config)
self.register_buffer('fix_std', torch.tensor(config.fix_std), persistent=False)
self.std_dist_type = getattr(config, "std_dist_type", "fix")
# Parse encoder depths
if isinstance(config.encoder_depths, str):
encoder_depths = [int(d) for d in config.encoder_depths.split('-')]
else:
encoder_depths = config.encoder_depths
# Parse decoder depths if provided
if config.decoder_depths is not None and isinstance(config.decoder_depths, str):
decoder_depths = [int(d) for d in config.decoder_depths.split('-')]
else:
# Default: use reversed encoder depths if decoder_depths is None
decoder_depths = list(reversed(encoder_depths))
# Create encoder config
encoder_config = copy.deepcopy(config)
encoder_config.dimension = config.vae_dim
encoder_config.n_filters = config.encoder_n_filters
encoder_config.ratios = config.encoder_ratios
encoder_config.depths = encoder_depths
encoder_config.norm = config.conv_norm
encoder_config.pad_mode = config.pad_mode
encoder_config.bias = config.conv_bias
encoder_config.layernorm_eps = config.layernorm_eps
encoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
encoder_config.mixer_layer = config.mixer_layer
encoder_config.layer_scale_init_value = config.layer_scale_init_value
encoder_config.disable_last_norm = config.disable_last_norm
# Create decoder config
decoder_config = copy.deepcopy(config)
decoder_config.dimension = config.vae_dim
decoder_config.n_filters = config.decoder_n_filters
decoder_config.ratios = config.decoder_ratios
decoder_config.depths = decoder_depths
decoder_config.norm = config.conv_norm
decoder_config.pad_mode = config.pad_mode
decoder_config.bias = config.conv_bias
decoder_config.layernorm_eps = config.layernorm_eps
decoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
decoder_config.mixer_layer = config.mixer_layer
decoder_config.layer_scale_init_value = config.layer_scale_init_value
decoder_config.disable_last_norm = config.disable_last_norm
# Initialize encoder and decoder
self.encoder = TokenizerEncoder(encoder_config)
self.decoder = TokenizerDecoder(decoder_config)
# Initialize weights
self.apply(self._init_weights)
def _init_weights(self, module):
"""Initialize weights for the model"""
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=self.config.weight_init_value)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Conv1d):
nn.init.normal_(module.weight, std=self.config.weight_init_value)
if module.bias is not None:
nn.init.zeros_(module.bias)
@torch.no_grad()
def encode(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False, is_final_chunk=False):
"""Convert audio to latent representations"""
latents = self.encoder(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
return VibeVoiceTokenizerEncoderOutput(mean=latents.permute(0, 2, 1), std=self.fix_std)
@torch.no_grad()
def sampling(self, encoder_output, dist_type=None):
"""Sample from the encoder output distribution"""
dist_type = dist_type or self.std_dist_type
if dist_type == 'fix':
return encoder_output.sample(dist_type='fix')
elif dist_type == 'gaussian':
return encoder_output.sample(dist_type='gaussian')
else:
raise ValueError(f"Unsupported dist_type: {dist_type}, expected 'fix' or 'gaussian'")
@torch.no_grad()
def decode(self, latents, cache=None, sample_indices=None, use_cache=False, debug=False):
"""Convert latent representations back to audio"""
if latents.shape[1] == self.config.vae_dim:
pass
else:
latents = latents.permute(0, 2, 1)
audio = self.decoder(latents, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
return audio
def forward(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
"""Full forward pass: encode audio to latents, then decode back to audio"""
encoder_output = self.encode(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
sampled_latents, _ = self.sampling(encoder_output)
reconstructed = self.decode(sampled_latents, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
return reconstructed, sampled_latents
class VibeVoiceSemanticTokenizerModel(PreTrainedModel):
"""VibeVoice speech tokenizer model with only encoder for semantic tokens"""
config_class = VibeVoiceSemanticTokenizerConfig
base_model_prefix = "vibevoice_semantic_tokenizer"
_supports_flash_attn_2 = True
_supports_sdpa = True
_no_split_modules = ["TokenizerEncoder"]
def __init__(self, config):
super().__init__(config)
# Parse encoder depths
if isinstance(config.encoder_depths, str):
encoder_depths = [int(d) for d in config.encoder_depths.split('-')]
else:
encoder_depths = config.encoder_depths
# Create encoder config
encoder_config = copy.deepcopy(config)
encoder_config.dimension = config.vae_dim
encoder_config.n_filters = config.encoder_n_filters
encoder_config.ratios = config.encoder_ratios
encoder_config.depths = encoder_depths
encoder_config.norm = config.conv_norm
encoder_config.pad_mode = config.pad_mode
encoder_config.bias = config.conv_bias
encoder_config.layernorm_eps = config.layernorm_eps
encoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
encoder_config.mixer_layer = config.mixer_layer
encoder_config.layer_scale_init_value = config.layer_scale_init_value
encoder_config.disable_last_norm = config.disable_last_norm
# Initialize encoder and decoder
self.encoder = TokenizerEncoder(encoder_config)
# Initialize weights
self.apply(self._init_weights)
def _init_weights(self, module):
"""Initialize weights for the model"""
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=self.config.weight_init_value)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Conv1d):
nn.init.normal_(module.weight, std=self.config.weight_init_value)
if module.bias is not None:
nn.init.zeros_(module.bias)
@torch.no_grad()
def encode(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False, is_final_chunk=False):
"""Convert audio to latent representations"""
latents = self.encoder(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug, is_final_chunk=is_final_chunk)
return VibeVoiceTokenizerEncoderOutput(mean=latents.permute(0, 2, 1))
@torch.no_grad()
def sampling(self, encoder_output, dist_type=None):
"""Sample from the encoder output distribution"""
return encoder_output.sample(dist_type='none')
def forward(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
"""Full forward pass: encode audio to latents, then decode back to audio"""
encoder_output = self.encode(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
sampled_latents, _ = self.sampling(encoder_output, dist_type='none')
return None, sampled_latents
AutoModel.register(VibeVoiceAcousticTokenizerConfig, VibeVoiceAcousticTokenizerModel)
AutoModel.register(VibeVoiceSemanticTokenizerConfig, VibeVoiceSemanticTokenizerModel)
__all__ = [
"VibeVoiceTokenizerStreamingCache",
"VibeVoiceAcousticTokenizerModel",
"VibeVoiceSemanticTokenizerModel",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/modular_vibevoice_tokenizer.py",
"license": "MIT License",
"lines": 1010,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/modular/streamer.py | from __future__ import annotations
import torch
import asyncio
from queue import Queue
from typing import TYPE_CHECKING, Optional
from transformers.generation import BaseStreamer
class AudioStreamer(BaseStreamer):
"""
Audio streamer that stores audio chunks in queues for each sample in the batch.
This allows streaming audio generation for multiple samples simultaneously.
Parameters:
batch_size (`int`):
The batch size for generation
stop_signal (`any`, *optional*):
The signal to put in the queue when generation ends. Defaults to None.
timeout (`float`, *optional*):
The timeout for the audio queue. If `None`, the queue will block indefinitely.
"""
def __init__(
self,
batch_size: int,
stop_signal: Optional[any] = None,
timeout: Optional[float] = None,
):
self.batch_size = batch_size
self.stop_signal = stop_signal
self.timeout = timeout
# Create a queue for each sample in the batch
self.audio_queues = [Queue() for _ in range(batch_size)]
self.finished_flags = [False for _ in range(batch_size)]
self.sample_indices_map = {} # Maps from sample index to queue index
def put(self, audio_chunks: torch.Tensor, sample_indices: torch.Tensor):
"""
Receives audio chunks and puts them in the appropriate queues.
Args:
audio_chunks: Tensor of shape (num_samples, ...) containing audio chunks
sample_indices: Tensor indicating which samples these chunks belong to
"""
for i, sample_idx in enumerate(sample_indices):
idx = sample_idx.item()
if idx < self.batch_size and not self.finished_flags[idx]:
# Convert to numpy or keep as tensor based on preference
audio_chunk = audio_chunks[i].detach().cpu()
self.audio_queues[idx].put(audio_chunk, timeout=self.timeout)
def end(self, sample_indices: Optional[torch.Tensor] = None):
"""
Signals the end of generation for specified samples or all samples.
Args:
sample_indices: Optional tensor of sample indices to end. If None, ends all.
"""
if sample_indices is None:
# End all samples
for idx in range(self.batch_size):
if not self.finished_flags[idx]:
self.audio_queues[idx].put(self.stop_signal, timeout=self.timeout)
self.finished_flags[idx] = True
else:
# End specific samples
for sample_idx in sample_indices:
idx = sample_idx.item() if torch.is_tensor(sample_idx) else sample_idx
if idx < self.batch_size and not self.finished_flags[idx]:
self.audio_queues[idx].put(self.stop_signal, timeout=self.timeout)
self.finished_flags[idx] = True
def __iter__(self):
"""Returns an iterator over the batch of audio streams."""
return AudioBatchIterator(self)
def get_stream(self, sample_idx: int):
"""Get the audio stream for a specific sample."""
if sample_idx >= self.batch_size:
raise ValueError(f"Sample index {sample_idx} exceeds batch size {self.batch_size}")
return AudioSampleIterator(self, sample_idx)
class AudioSampleIterator:
"""Iterator for a single audio stream from the batch."""
def __init__(self, streamer: AudioStreamer, sample_idx: int):
self.streamer = streamer
self.sample_idx = sample_idx
def __iter__(self):
return self
def __next__(self):
value = self.streamer.audio_queues[self.sample_idx].get(timeout=self.streamer.timeout)
if value == self.streamer.stop_signal:
raise StopIteration()
return value
class AudioBatchIterator:
"""Iterator that yields audio chunks for all samples in the batch."""
def __init__(self, streamer: AudioStreamer):
self.streamer = streamer
self.active_samples = set(range(streamer.batch_size))
def __iter__(self):
return self
def __next__(self):
if not self.active_samples:
raise StopIteration()
batch_chunks = {}
samples_to_remove = set()
# Try to get chunks from all active samples
for idx in self.active_samples:
try:
value = self.streamer.audio_queues[idx].get(block=False)
if value == self.streamer.stop_signal:
samples_to_remove.add(idx)
else:
batch_chunks[idx] = value
except:
# Queue is empty for this sample, skip it this iteration
pass
# Remove finished samples
self.active_samples -= samples_to_remove
if batch_chunks:
return batch_chunks
elif self.active_samples:
# If no chunks were ready but we still have active samples,
# wait a bit and try again
import time
time.sleep(0.01)
return self.__next__()
else:
raise StopIteration()
class AsyncAudioStreamer(AudioStreamer):
"""
Async version of AudioStreamer for use in async contexts.
"""
def __init__(
self,
batch_size: int,
stop_signal: Optional[any] = None,
timeout: Optional[float] = None,
):
super().__init__(batch_size, stop_signal, timeout)
# Replace regular queues with async queues
self.audio_queues = [asyncio.Queue() for _ in range(batch_size)]
self.loop = asyncio.get_running_loop()
def put(self, audio_chunks: torch.Tensor, sample_indices: torch.Tensor):
"""Put audio chunks in the appropriate async queues."""
for i, sample_idx in enumerate(sample_indices):
idx = sample_idx.item()
if idx < self.batch_size and not self.finished_flags[idx]:
audio_chunk = audio_chunks[i].detach().cpu()
self.loop.call_soon_threadsafe(
self.audio_queues[idx].put_nowait, audio_chunk
)
def end(self, sample_indices: Optional[torch.Tensor] = None):
"""Signal the end of generation for specified samples."""
if sample_indices is None:
indices_to_end = range(self.batch_size)
else:
indices_to_end = [s.item() if torch.is_tensor(s) else s for s in sample_indices]
for idx in indices_to_end:
if idx < self.batch_size and not self.finished_flags[idx]:
self.loop.call_soon_threadsafe(
self.audio_queues[idx].put_nowait, self.stop_signal
)
self.finished_flags[idx] = True
async def get_stream(self, sample_idx: int):
"""Get async iterator for a specific sample's audio stream."""
if sample_idx >= self.batch_size:
raise ValueError(f"Sample index {sample_idx} exceeds batch size {self.batch_size}")
while True:
value = await self.audio_queues[sample_idx].get()
if value == self.stop_signal:
break
yield value
def __aiter__(self):
"""Returns an async iterator over all audio streams."""
return AsyncAudioBatchIterator(self)
class AsyncAudioBatchIterator:
"""Async iterator for batch audio streaming."""
def __init__(self, streamer: AsyncAudioStreamer):
self.streamer = streamer
self.active_samples = set(range(streamer.batch_size))
def __aiter__(self):
return self
async def __anext__(self):
if not self.active_samples:
raise StopAsyncIteration()
batch_chunks = {}
samples_to_remove = set()
# Create tasks for all active samples
tasks = {
idx: asyncio.create_task(self._get_chunk(idx))
for idx in self.active_samples
}
# Wait for at least one chunk to be ready
done, pending = await asyncio.wait(
tasks.values(),
return_when=asyncio.FIRST_COMPLETED,
timeout=self.streamer.timeout
)
# Cancel pending tasks
for task in pending:
task.cancel()
# Process completed tasks
for idx, task in tasks.items():
if task in done:
try:
value = await task
if value == self.streamer.stop_signal:
samples_to_remove.add(idx)
else:
batch_chunks[idx] = value
except asyncio.CancelledError:
pass
self.active_samples -= samples_to_remove
if batch_chunks:
return batch_chunks
elif self.active_samples:
# Try again if we still have active samples
return await self.__anext__()
else:
raise StopAsyncIteration()
async def _get_chunk(self, idx):
"""Helper to get a chunk from a specific queue."""
return await self.streamer.audio_queues[idx].get() | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/modular/streamer.py",
"license": "MIT License",
"lines": 213,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/processor/vibevoice_processor.py | import math
import warnings
from typing import List, Optional, Union, Dict, Any, Tuple
import os
import re
import numpy as np
import torch
from transformers.tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from transformers.utils import TensorType, logging
from .vibevoice_tokenizer_processor import AudioNormalizer
logger = logging.get_logger(__name__)
class VibeVoiceProcessor:
r"""
Constructs a VibeVoice processor which wraps a VibeVoice tokenizer and audio processor into a single processor.
[`VibeVoiceProcessor`] offers all the functionalities of [`VibeVoiceTokenizer`] and [`VibeVoiceTokenizerProcessor`].
See the [`~VibeVoiceProcessor.__call__`] and [`~VibeVoiceProcessor.decode`] for more information.
Args:
tokenizer (`VibeVoiceTextTokenizer` or `VibeVoiceTextTokenizerFast`):
The tokenizer for text processing.
audio_processor (`VibeVoiceTokenizerProcessor`):
The audio processor for speech processing.
speech_tok_compress_ratio (`int`, *optional*, defaults to 3200):
The compression ratio for speech tokenization.
db_normalize (`bool`, *optional*, defaults to True):
Whether to apply decibel normalization to audio inputs.
"""
def __init__(self, tokenizer=None, audio_processor=None, speech_tok_compress_ratio=3200, db_normalize=True, **kwargs):
self.tokenizer = tokenizer
self.audio_processor = audio_processor
self.speech_tok_compress_ratio = speech_tok_compress_ratio
self.db_normalize = db_normalize
self.audio_normalizer = AudioNormalizer() if db_normalize else None
self.system_prompt = " Transform the text provided by various speakers into speech output, utilizing the distinct voice of each respective speaker.\n"
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
"""
Instantiate a VibeVoiceProcessor from a pretrained VibeVoice processor.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained model
- a path to a *directory* containing processor config
Returns:
[`VibeVoiceProcessor`]: The processor object instantiated from pretrained model.
"""
import os
import json
from transformers.utils import cached_file
from .vibevoice_tokenizer_processor import VibeVoiceTokenizerProcessor
from vibevoice.modular.modular_vibevoice_text_tokenizer import (
VibeVoiceTextTokenizer,
VibeVoiceTextTokenizerFast
)
# Try to load from local path first, then from HF hub
config_path = os.path.join(pretrained_model_name_or_path, "preprocessor_config.json")
config = None
if os.path.exists(config_path):
# Local path exists
with open(config_path, 'r') as f:
config = json.load(f)
else:
# Try to load from HF hub
try:
config_file = cached_file(
pretrained_model_name_or_path,
"preprocessor_config.json",
**kwargs
)
with open(config_file, 'r') as f:
config = json.load(f)
except Exception as e:
logger.warning(f"Could not load preprocessor_config.json from {pretrained_model_name_or_path}: {e}")
logger.warning("Using default configuration")
config = {
"speech_tok_compress_ratio": 3200,
"db_normalize": True,
}
# Extract main processor parameters
speech_tok_compress_ratio = config.get("speech_tok_compress_ratio", 3200)
db_normalize = config.get("db_normalize", True)
# Load tokenizer - try from model path first, then fallback to Qwen
language_model_pretrained_name = config.get("language_model_pretrained_name", None) or kwargs.pop("language_model_pretrained_name", "Qwen/Qwen2.5-1.5B")
logger.info(f"Loading tokenizer from {language_model_pretrained_name}")
if 'qwen' in language_model_pretrained_name.lower():
tokenizer = VibeVoiceTextTokenizerFast.from_pretrained(
language_model_pretrained_name,
**kwargs
)
else:
raise ValueError(f"Unsupported tokenizer type for {language_model_pretrained_name}. Supported types: Qwen, Llama, Gemma.")
# Load audio processor
if "audio_processor" in config:
# Create audio processor from config
audio_config = config["audio_processor"]
audio_processor = VibeVoiceTokenizerProcessor(
sampling_rate=audio_config.get("sampling_rate", 24000),
normalize_audio=audio_config.get("normalize_audio", True),
target_dB_FS=audio_config.get("target_dB_FS", -25),
eps=audio_config.get("eps", 1e-6),
)
else:
# Create default audio processor
audio_processor = VibeVoiceTokenizerProcessor()
# Create and return the processor
return cls(
tokenizer=tokenizer,
audio_processor=audio_processor,
speech_tok_compress_ratio=speech_tok_compress_ratio,
db_normalize=db_normalize,
)
def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
"""
Save a processor to a directory, so that it can be re-loaded using the
[`~VibeVoiceProcessor.from_pretrained`] class method.
Args:
save_directory (`str` or `os.PathLike`):
Directory where the processor will be saved.
"""
import os
import json
os.makedirs(save_directory, exist_ok=True)
# Save processor configuration
processor_config = {
"processor_class": "VibeVoiceProcessor",
"speech_tok_compress_ratio": self.speech_tok_compress_ratio,
"db_normalize": self.db_normalize,
"audio_processor": {
"feature_extractor_type": "VibeVoiceTokenizerProcessor",
"sampling_rate": getattr(self.audio_processor, 'sampling_rate', 24000),
"normalize_audio": getattr(self.audio_processor, 'normalize_audio', True),
"target_dB_FS": getattr(self.audio_processor, 'target_dB_FS', -25),
"eps": getattr(self.audio_processor, 'eps', 1e-6),
}
}
config_path = os.path.join(save_directory, "preprocessor_config.json")
with open(config_path, 'w') as f:
json.dump(processor_config, f, indent=2)
logger.info(f"Processor configuration saved in {config_path}")
def __call__(
self,
text: Optional[Union[str, List[str], TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
voice_samples: Optional[Union[List[Union[str, np.ndarray]], List[List[Union[str, np.ndarray]]]]] = None,
padding: Union[bool, str, PaddingStrategy] = True,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_attention_mask: bool = True,
**kwargs,
) -> BatchEncoding:
"""
Main method to process one or more podcast scripts with optional voice samples.
Args:
text (`str`, `List[str]`):
The input text(s) to process. Can be:
- A single script string
- A list of script strings for batch processing
- A path to a .json or .txt file
- A list of paths
voice_samples (`List[Union[str, np.ndarray]]`, `List[List[Union[str, np.ndarray]]]`, *optional*):
Voice samples for each script. Can be:
- A list of samples for a single script
- A list of lists for batch processing
padding (`bool`, `str` or `PaddingStrategy`, defaults to `True`):
Whether to pad sequences to the same length
truncation (`bool`, `str` or `TruncationStrategy`, defaults to `False`):
Whether to truncate sequences
max_length (`int`, *optional*):
Maximum length of the returned sequences
return_tensors (`str` or `TensorType`, *optional*):
If set, will return tensors of a particular framework
return_attention_mask (`bool`, defaults to `True`):
Whether to return the attention mask
Returns:
`BatchEncoding`: A BatchEncoding with the following fields:
- **input_ids** -- List of token id sequences or tensor
- **attention_mask** -- List of attention masks or tensor
- **speech_tensors** -- Padded speech inputs (if voice_samples provided)
- **speech_masks** -- Speech masks (if voice_samples provided)
- **speech_input_mask** -- Boolean masks indicating speech token positions
"""
# Handle single vs batch input
if isinstance(text, str) or (isinstance(text, list) and len(text) > 0 and not isinstance(text[0], str)):
# Single input
texts = [text]
is_batched = False
else:
# Batch input
texts = text
is_batched = True
# Handle voice samples
if voice_samples is not None:
if not is_batched or (isinstance(voice_samples[0], (str, np.ndarray))):
# Single set of voice samples
voice_samples_list = [voice_samples]
else:
# Batch of voice samples
voice_samples_list = voice_samples
else:
voice_samples_list = [None] * len(texts)
# Process each input
all_encodings = []
for text_input, voice_input in zip(texts, voice_samples_list):
encoding = self._process_single(text_input, voice_input)
all_encodings.append(encoding)
# Combine batch
batch_encoding = self._batch_encode(
all_encodings,
padding=padding,
truncation=truncation,
max_length=max_length,
return_tensors=return_tensors,
return_attention_mask=return_attention_mask,
)
return batch_encoding
def _process_single(
self,
text: Union[str, TextInput],
voice_samples: Optional[List[Union[str, np.ndarray]]] = None,
) -> Dict[str, Any]:
"""Process a single podcast script."""
# Determine if text is a file path or direct script
script = None
if isinstance(text, str):
# Check if it's a file path
if text.endswith('.json') and os.path.exists(text):
script = self._convert_json_to_script(text)
elif text.endswith('.txt') and os.path.exists(text):
script = self._convert_text_to_script(text)
else:
# Assume it's the script content directly
script = text
if script is None:
raise ValueError(f"Could not process input text: {text}")
# Parse the script
parsed_lines = self._parse_script(script)
all_speakers = list(set(speaker_id for speaker_id, _ in parsed_lines))
# Create system prompt
# system_tokens = self.tokenizer.encode(self.system_prompt, add_special_tokens=False)
system_tokens = self.tokenizer.encode(self.system_prompt)
# Process voice samples if provided
if voice_samples:
voice_tokens, voice_speech_inputs, voice_speech_masks = self._create_voice_prompt(voice_samples[:len(all_speakers)])
else:
voice_tokens, voice_speech_inputs, voice_speech_masks = [], [], []
# Build full token sequence
full_tokens = system_tokens + voice_tokens
speech_input_mask = [False] * len(system_tokens) + voice_speech_masks
# Add text input section
full_tokens += self.tokenizer.encode(' Text input:\n', add_special_tokens=False)
speech_input_mask += [False] * len(self.tokenizer.encode(' Text input:\n', add_special_tokens=False))
for speaker_id, speaker_text in parsed_lines:
speaker_text_tokens = self.tokenizer.encode(f" Speaker {speaker_id}:{speaker_text}\n", add_special_tokens=False)
full_tokens += speaker_text_tokens
speech_input_mask += [False] * len(speaker_text_tokens)
# Add speech output section
full_tokens += self.tokenizer.encode(' Speech output:\n', add_special_tokens=False) + [self.tokenizer.speech_start_id]
speech_input_mask += [False] * (len(self.tokenizer.encode(' Speech output:\n', add_special_tokens=False)) + 1)
return {
"input_ids": full_tokens,
"speech_inputs": voice_speech_inputs if voice_speech_inputs else None,
"speech_input_mask": speech_input_mask,
"parsed_script": parsed_lines,
"all_speakers": all_speakers,
}
def _batch_encode(
self,
encodings: List[Dict[str, Any]],
padding: Union[bool, str, PaddingStrategy] = True,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_attention_mask: bool = True,
) -> BatchEncoding:
"""Combine multiple encodings into a batch with padding."""
# Extract input_ids and create attention_mask
input_ids_list = [enc["input_ids"] for enc in encodings]
speech_input_masks_list = [enc["speech_input_mask"] for enc in encodings]
# Determine padding strategy
if isinstance(padding, bool):
padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
elif isinstance(padding, str):
padding_strategy = PaddingStrategy(padding)
else:
padding_strategy = padding
# Apply padding to input_ids
if padding_strategy != PaddingStrategy.DO_NOT_PAD:
if padding_strategy == PaddingStrategy.LONGEST:
max_len = max(len(ids) for ids in input_ids_list)
elif padding_strategy == PaddingStrategy.MAX_LENGTH and max_length is not None:
max_len = max_length
else:
max_len = max(len(ids) for ids in input_ids_list)
# Pad sequences
padded_input_ids = []
attention_masks = []
padded_speech_input_masks = []
for input_ids, speech_mask in zip(input_ids_list, speech_input_masks_list):
# Truncate if needed
if truncation and len(input_ids) > max_len:
input_ids = input_ids[:max_len]
speech_mask = speech_mask[:max_len]
# Pad
padding_length = max_len - len(input_ids)
# padded_ids = [self.tokenizer.pad_token_id] * padding_length + input_ids
padded_ids = [self.tokenizer.pad_id] * padding_length + input_ids
attention_mask = [0] * padding_length + [1] * len(input_ids)
padded_speech_mask = [False] * padding_length + speech_mask
padded_input_ids.append(padded_ids)
attention_masks.append(attention_mask)
padded_speech_input_masks.append(padded_speech_mask)
input_ids_list = padded_input_ids
speech_input_masks_list = padded_speech_input_masks
else:
# No padding, just create attention masks
attention_masks = [[1] * len(ids) for ids in input_ids_list] if return_attention_mask else None
# Process speech inputs
all_speech_inputs = []
has_speech = False
for enc in encodings:
if enc["speech_inputs"] is not None:
all_speech_inputs.extend(enc["speech_inputs"])
has_speech = True
# Prepare batch encoding
batch_encoding = BatchEncoding()
# Handle tensor conversion
if return_tensors is not None:
batch_encoding["input_ids"] = torch.tensor(input_ids_list, dtype=torch.long)
if return_attention_mask and attention_masks is not None:
batch_encoding["attention_mask"] = torch.tensor(attention_masks, dtype=torch.long)
batch_encoding["speech_input_mask"] = torch.tensor(speech_input_masks_list, dtype=torch.bool)
else:
batch_encoding["input_ids"] = input_ids_list
if return_attention_mask and attention_masks is not None:
batch_encoding["attention_mask"] = attention_masks
batch_encoding["speech_input_mask"] = speech_input_masks_list
# Process speech tensors if present
if has_speech:
speech_dict = self.prepare_speech_inputs(
all_speech_inputs,
return_tensors=return_tensors,
)
batch_encoding["speech_tensors"] = speech_dict["padded_speeches"]
batch_encoding["speech_masks"] = speech_dict["speech_masks"]
else:
batch_encoding["speech_tensors"] = None
batch_encoding["speech_masks"] = None
# Add metadata
batch_encoding["parsed_scripts"] = [enc["parsed_script"] for enc in encodings]
batch_encoding["all_speakers_list"] = [enc["all_speakers"] for enc in encodings]
return batch_encoding
def _create_voice_prompt(
self,
speaker_samples: List[Union[str, np.ndarray]]
) -> Tuple[List[int], List[np.ndarray], List[bool]]:
"""
Create voice prompt tokens and process audio samples.
Returns:
tuple: (voice_tokens, voice_speech_inputs, voice_speech_masks)
"""
vae_token_id = self.tokenizer.speech_diffusion_id
voice_full_tokens = self.tokenizer.encode(' Voice input:\n', add_special_tokens=False)
voice_speech_inputs = []
voice_speech_masks = [False] * len(voice_full_tokens)
for speaker_id, speaker_audio in enumerate(speaker_samples):
prefix_tokens = self.tokenizer.encode(f" Speaker {speaker_id}:", add_special_tokens=False)
# Process audio
if isinstance(speaker_audio, str):
# Load audio from file
wav = self.audio_processor._load_audio_from_path(speaker_audio)
else:
wav = np.array(speaker_audio, dtype=np.float32)
# Apply normalization if needed
if self.db_normalize and self.audio_normalizer:
wav = self.audio_normalizer(wav)
# Calculate token length based on compression ratio
# if speaker_audio.endswith('.pt') or speaker_audio.endswith('.npy'):
# vae_tok_len = wav.shape[0]
# else:
vae_tok_len = math.ceil(wav.shape[0] / self.speech_tok_compress_ratio)
# Build tokens and masks
speaker_tokens = (prefix_tokens +
[self.tokenizer.speech_start_id] +
[vae_token_id] * vae_tok_len +
[self.tokenizer.speech_end_id] +
self.tokenizer.encode('\n', add_special_tokens=False))
vae_input_mask = ([False] * len(prefix_tokens) +
[False] +
[True] * vae_tok_len +
[False] +
[False])
voice_full_tokens.extend(speaker_tokens)
voice_speech_masks.extend(vae_input_mask)
voice_speech_inputs.append(wav)
return voice_full_tokens, voice_speech_inputs, voice_speech_masks
def prepare_speech_inputs(
self,
speech_inputs: List[np.ndarray],
return_tensors: Optional[Union[str, TensorType]] = None,
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> Dict[str, Any]:
"""
Prepare speech inputs for model consumption.
Args:
speech_inputs: List of speech arrays
return_tensors: Output tensor type
device: Device to place tensors on
dtype: Data type for tensors
Returns:
Dictionary with padded_speeches and speech_masks
"""
if not speech_inputs:
return {"padded_speeches": None, "speech_masks": None}
# Calculate sequence lengths
vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) for s in speech_inputs]
# vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) if s.ndim == 1 else s.shape[0] for s in speech_inputs]
max_speech_length = max(s.shape[0] for s in speech_inputs)
# Pad speeches
if speech_inputs[0].ndim == 1:
padded_speeches = np.full((len(speech_inputs), max_speech_length), fill_value=0, dtype=np.float32)
else:
padded_speeches = np.full((len(speech_inputs), max_speech_length, speech_inputs[0].shape[-1]), fill_value=0, dtype=np.float32)
speech_masks = np.zeros((len(speech_inputs), max(vae_tok_seqlens)), dtype=np.bool_)
for i, (speech, vae_tok_length) in enumerate(zip(speech_inputs, vae_tok_seqlens)):
padded_speeches[i, :len(speech)] = speech
speech_masks[i, :vae_tok_length] = True
result = {
"padded_speeches": padded_speeches,
"speech_masks": speech_masks,
}
# Convert to tensors if requested
if return_tensors == "pt":
result["padded_speeches"] = torch.tensor(padded_speeches, device=device, dtype=dtype or torch.float32)
result["speech_masks"] = torch.tensor(speech_masks, device=device, dtype=torch.bool)
return result
def _convert_json_to_script(self, json_file: str) -> str:
"""
Convert JSON format to script format.
Expected JSON format:
[
{"speaker": "1", "text": "Hello everyone..."},
{"speaker": "2", "text": "Great to be here..."}
]
"""
import json
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
if not isinstance(data, list):
raise ValueError("JSON file must contain a list of speaker entries")
script_lines = []
for item in data:
if not isinstance(item, dict):
logger.warning(f"Skipping non-dict entry: {item}")
continue
speaker = item.get('speaker')
text = item.get('text')
if speaker is None or text is None:
logger.warning(f"Skipping entry missing speaker or text: {item}")
continue
# Ensure speaker ID is valid
try:
speaker_id = int(speaker)
except (ValueError, TypeError):
logger.warning(f"Invalid speaker ID: {speaker}, skipping entry")
continue
# Clean up text
text = text.strip()
if text:
script_lines.append(f"Speaker {speaker_id}: {text}")
if not script_lines:
raise ValueError("No valid entries found in JSON file")
return "\n".join(script_lines)
def _convert_text_to_script(self, text_file: str) -> str:
"""
Convert text file to script format.
Handles multiple formats:
1. Already formatted as "Speaker X: text"
2. Plain text (assigns to Speaker 1)
Handles edge cases like multiple colons in a line.
"""
with open(text_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
script_lines = []
current_speaker = 1
for line in lines:
line = line.strip()
if not line:
continue
# Try to parse as "Speaker X: text" format
# Use regex to be more robust
speaker_match = re.match(r'^Speaker\s+(\d+)\s*:\s*(.*)$', line, re.IGNORECASE)
if speaker_match:
speaker_id = int(speaker_match.group(1))
text = speaker_match.group(2).strip()
if text:
script_lines.append(f"Speaker {speaker_id}: {text}")
else:
# Treat as plain text - assign to current speaker
script_lines.append(f"Speaker {current_speaker}: {line}")
if not script_lines:
raise ValueError("No valid content found in text file")
return "\n".join(script_lines)
def _parse_script(self, script: str) -> List[Tuple[int, str]]:
"""Parse script into list of (speaker_id, text) tuples."""
lines = script.strip().split("\n")
parsed_lines = []
speaker_ids = []
# First pass: parse all lines and collect speaker IDs
for line in lines:
if not line.strip():
continue
# Use regex to handle edge cases like multiple colons
match = re.match(r'^Speaker\s+(\d+)\s*:\s*(.*)$', line.strip(), re.IGNORECASE)
if match:
speaker_id = int(match.group(1))
text = ' ' + match.group(2).strip()
parsed_lines.append((speaker_id, text))
speaker_ids.append(speaker_id)
else:
logger.warning(f"Could not parse line: '{line}'")
if not parsed_lines:
raise ValueError("No valid speaker lines found in script")
# Check if we need to normalize speaker IDs (only if all are > 0)
min_speaker_id = min(speaker_ids)
if min_speaker_id > 0:
# Normalize to start from 0
normalized_lines = []
for speaker_id, text in parsed_lines:
normalized_lines.append((speaker_id - 1, text))
return normalized_lines
else:
# Keep original IDs
return parsed_lines
def _merge_inputs(self, text_inputs: BatchEncoding, audio_inputs: Dict) -> BatchEncoding:
"""Merge text and audio inputs into a single BatchEncoding."""
# Start with text inputs
merged = BatchEncoding(text_inputs)
# Add audio-specific fields
if "audio" in audio_inputs:
merged["speech_inputs"] = audio_inputs["audio"]
if "streaming" in audio_inputs:
merged["streaming"] = audio_inputs["streaming"]
return merged
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.batch_decode`].
Please refer to the docstring of this method for more information.
"""
return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.decode`].
Please refer to the docstring of this method for more information.
"""
return self.tokenizer.decode(*args, **kwargs)
@property
def model_input_names(self):
"""
Return the list of inputs accepted by the model.
"""
tokenizer_input_names = self.tokenizer.model_input_names
audio_processor_input_names = self.audio_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + audio_processor_input_names + ["speech_inputs", "speech_input_mask"]))
def save_audio(self,
audio: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]],
output_path: str = "output.wav",
sampling_rate: Optional[int] = None,
normalize: bool = False,
batch_prefix: str = "audio_",
) -> str:
"""
Save audio data to a file.
Args:
audio (Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]]):
The audio data to save. Can be a single tensor/array or a list of them.
output_path (str, optional): Path to save the audio file. Defaults to "output.wav".
sampling_rate (int, optional): Sampling rate for the audio. If None, uses the processor's default.
normalize (bool, optional): Whether to normalize the audio before saving. Defaults to False.
batch_prefix (str, optional): Prefix for batch audio files. Defaults to "audio_".
Returns:
str: The path to the saved audio file.
"""
return self.audio_processor.save_audio(audio, output_path=output_path, sampling_rate=sampling_rate, normalize=normalize, batch_prefix=batch_prefix)
__all__ = [
"VibeVoiceProcessor",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/processor/vibevoice_processor.py",
"license": "MIT License",
"lines": 586,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/processor/vibevoice_streaming_processor.py | import math
import warnings
from typing import List, Optional, Union, Dict, Any, Tuple
import os
import re
import numpy as np
import torch
from transformers.tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from transformers.utils import TensorType, logging
from .vibevoice_tokenizer_processor import AudioNormalizer
logger = logging.get_logger(__name__)
class VibeVoiceStreamingProcessor:
r"""
Constructs a VibeVoice Streaming processor which wraps a VibeVoice tokenizer and audio processor into a single processor.
Args:
tokenizer (`VibeVoiceTextTokenizer` or `VibeVoiceTextTokenizerFast`):
The tokenizer for text processing.
audio_processor (`VibeVoiceTokenizerProcessor`):
The audio processor for speech processing.
speech_tok_compress_ratio (`int`, *optional*, defaults to 3200):
The compression ratio for speech tokenization.
db_normalize (`bool`, *optional*, defaults to True):
Whether to apply decibel normalization to audio inputs.
"""
def __init__(self, tokenizer=None, audio_processor=None, speech_tok_compress_ratio=3200, db_normalize=True, **kwargs):
self.tokenizer = tokenizer
self.audio_processor = audio_processor
self.speech_tok_compress_ratio = speech_tok_compress_ratio
self.db_normalize = db_normalize
self.audio_normalizer = AudioNormalizer() if db_normalize else None
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
"""
Instantiate a VibeVoiceStreamingProcessor from a pretrained VibeVoice Streaming processor.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained model
- a path to a *directory* containing processor config
Returns:
[`VibeVoiceStreamingProcessor`]: The processor object instantiated from pretrained model.
"""
import os
import json
from transformers.utils import cached_file
from .vibevoice_tokenizer_processor import VibeVoiceTokenizerProcessor
from vibevoice.modular.modular_vibevoice_text_tokenizer import (
VibeVoiceTextTokenizer,
VibeVoiceTextTokenizerFast
)
# Try to load from local path first, then from HF hub
config_path = os.path.join(pretrained_model_name_or_path, "preprocessor_config.json")
config = None
if os.path.exists(config_path):
# Local path exists
with open(config_path, 'r') as f:
config = json.load(f)
else:
# Try to load from HF hub
try:
config_file = cached_file(
pretrained_model_name_or_path,
"preprocessor_config.json",
**kwargs
)
with open(config_file, 'r') as f:
config = json.load(f)
except Exception as e:
logger.warning(f"Could not load preprocessor_config.json from {pretrained_model_name_or_path}: {e}")
logger.warning("Using default configuration")
config = {
"speech_tok_compress_ratio": 3200,
"db_normalize": True,
}
# Extract main processor parameters
speech_tok_compress_ratio = config.get("speech_tok_compress_ratio", 3200)
db_normalize = config.get("db_normalize", True)
# Load tokenizer - try from model path first, then fallback to Qwen
language_model_pretrained_name = config.get("language_model_pretrained_name", None) or kwargs.pop("language_model_pretrained_name", "Qwen/Qwen2.5-1.5B")
logger.info(f"Loading tokenizer from {language_model_pretrained_name}")
if 'qwen' in language_model_pretrained_name.lower():
tokenizer = VibeVoiceTextTokenizerFast.from_pretrained(
language_model_pretrained_name,
**kwargs
)
else:
raise ValueError(f"Unsupported tokenizer type for {language_model_pretrained_name}. Supported types: Qwen, Llama, Gemma.")
# Load audio processor
if "audio_processor" in config:
# Create audio processor from config
audio_config = config["audio_processor"]
audio_processor = VibeVoiceTokenizerProcessor(
sampling_rate=audio_config.get("sampling_rate", 24000),
normalize_audio=audio_config.get("normalize_audio", True),
target_dB_FS=audio_config.get("target_dB_FS", -25),
eps=audio_config.get("eps", 1e-6),
)
else:
# Create default audio processor
audio_processor = VibeVoiceTokenizerProcessor()
# Create and return the processor
return cls(
tokenizer=tokenizer,
audio_processor=audio_processor,
speech_tok_compress_ratio=speech_tok_compress_ratio,
db_normalize=db_normalize,
)
def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
"""
Save a processor to a directory, so that it can be re-loaded using the
[`~VibeVoiceStreamingProcessor.from_pretrained`] class method.
Args:
save_directory (`str` or `os.PathLike`):
Directory where the processor will be saved.
"""
import os
import json
os.makedirs(save_directory, exist_ok=True)
# Save processor configuration
processor_config = {
"processor_class": "VibeVoiceStreamingProcessor",
"speech_tok_compress_ratio": self.speech_tok_compress_ratio,
"db_normalize": self.db_normalize,
"audio_processor": {
"feature_extractor_type": "VibeVoiceTokenizerProcessor",
"sampling_rate": getattr(self.audio_processor, 'sampling_rate', 24000),
"normalize_audio": getattr(self.audio_processor, 'normalize_audio', True),
"target_dB_FS": getattr(self.audio_processor, 'target_dB_FS', -25),
"eps": getattr(self.audio_processor, 'eps', 1e-6),
}
}
config_path = os.path.join(save_directory, "preprocessor_config.json")
with open(config_path, 'w') as f:
json.dump(processor_config, f, indent=2)
logger.info(f"Processor configuration saved in {config_path}")
def __call__(self) -> BatchEncoding:
"""
Note:
This method is intentionally not implemented in the streaming processor.
Use `process_input_with_cached_prompt` for streaming use cases.
"""
raise NotImplementedError(
"VibeVoiceStreamingProcessor.__call__ is not implemented. "
"Use process_input_with_cached_prompt for streaming inputs."
)
def process_input_with_cached_prompt(
self,
text: Optional[str] = None,
cached_prompt: Optional[Dict[str, Any]] = None,
padding: Union[bool, str, PaddingStrategy] = True,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_attention_mask: bool = True,
**kwargs,
) -> BatchEncoding:
"""
Main method to process one text script based on cached prompt. The function currently only supports single examples.
Args:
text (`str`):
The input text to process.
cached_prompt (`Dict[str, Any]`, *optional*):
The cached prompt to use for processing. It contains the kv cache of the voice prompt.
padding (`bool`, `str` or `PaddingStrategy`, defaults to `True`):
Whether to pad sequences to the same length
truncation (`bool`, `str` or `TruncationStrategy`, defaults to `False`):
Whether to truncate sequences
max_length (`int`, *optional*):
Maximum length of the returned sequences
return_tensors (`str` or `TensorType`, *optional*):
If set, will return tensors of a particular framework
return_attention_mask (`bool`, defaults to `True`):
Whether to return the attention mask
Returns:
`BatchEncoding`: A BatchEncoding with the following fields:
- **input_ids** -- List of token id sequences or tensor
- **attention_mask** -- List of attention masks or tensor
- **tts_lm_input_ids** -- List of token id sequences or tensor used for TTS LM
- **tts_lm_attention_mask** -- List of attention masks or tensor used for TTS LM
- **tts_text_ids** -- List of token id sequences or tensor for TTS text input
- **speech_tensors** -- Padded speech inputs (if voice_samples provided)
- **speech_masks** -- Speech masks (if voice_samples provided)
- **speech_input_mask** -- Boolean masks indicating speech token positions
"""
# Only support single example
texts = [text]
cached_prompts = [cached_prompt]
is_batched = False
# Process each input
all_encodings = []
for text_input, cached_prompt_input in zip(texts, cached_prompts):
script_tokens = self.tokenizer.encode(text_input.strip() + "\n", add_special_tokens=False)
input_id_length = cached_prompt_input['lm']['last_hidden_state'].size(1)
tts_lm_input_id_length = cached_prompt_input['tts_lm']['last_hidden_state'].size(1)
# psudo input ids and masks
input_ids = [self.tokenizer.pad_id] * input_id_length
tts_lm_input_ids = [self.tokenizer.pad_id] * tts_lm_input_id_length
speech_input_mask = [False] * tts_lm_input_id_length
encoding = {
"input_ids": input_ids,
"tts_lm_input_ids": tts_lm_input_ids,
"tts_text_ids": script_tokens,
"speech_inputs": None,
"speech_input_mask": speech_input_mask,
}
all_encodings.append(encoding)
# Combine batch
batch_encoding = self._batch_encode(
all_encodings,
padding=padding,
truncation=truncation,
max_length=max_length,
return_tensors=return_tensors,
return_attention_mask=return_attention_mask,
)
return batch_encoding
def _batch_encode(
self,
encodings: List[Dict[str, Any]],
padding: Union[bool, str, PaddingStrategy] = True,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_attention_mask: bool = True,
) -> BatchEncoding:
"""Combine multiple encodings into a batch with padding."""
# Extract input_ids and create attention_mask
input_ids_list = [enc["input_ids"] for enc in encodings]
tts_lm_input_ids_list = [enc["tts_lm_input_ids"] for enc in encodings]
tts_text_ids_list = [enc["tts_text_ids"] for enc in encodings]
speech_input_masks_list = [enc["speech_input_mask"] for enc in encodings]
attention_masks = [[1] * len(ids) for ids in input_ids_list] if return_attention_mask else None
tts_lm_attention_masks = [[1] * len(ids) for ids in tts_lm_input_ids_list] if return_attention_mask else None
# Process speech inputs
all_speech_inputs = []
has_speech = False
for enc in encodings:
if enc["speech_inputs"] is not None:
all_speech_inputs.extend(enc["speech_inputs"])
has_speech = True
# Prepare batch encoding
batch_encoding = BatchEncoding()
# Handle tensor conversion
if return_tensors is not None:
batch_encoding["input_ids"] = torch.tensor(input_ids_list, dtype=torch.long)
batch_encoding["tts_lm_input_ids"] = torch.tensor(tts_lm_input_ids_list, dtype=torch.long)
batch_encoding["tts_text_ids"] = torch.tensor(tts_text_ids_list, dtype=torch.long)
if return_attention_mask and attention_masks is not None:
batch_encoding["attention_mask"] = torch.tensor(attention_masks, dtype=torch.long)
batch_encoding["tts_lm_attention_mask"] = torch.tensor(tts_lm_attention_masks, dtype=torch.long)
batch_encoding["speech_input_mask"] = torch.tensor(speech_input_masks_list, dtype=torch.bool)
else:
batch_encoding["input_ids"] = input_ids_list
batch_encoding["tts_lm_input_ids"] = tts_lm_input_ids_list
batch_encoding["tts_text_ids"] = tts_text_ids_list
if return_attention_mask and attention_masks is not None:
batch_encoding["attention_mask"] = attention_masks
batch_encoding["tts_lm_attention_mask"] = tts_lm_attention_masks
batch_encoding["speech_input_mask"] = speech_input_masks_list
# Process speech tensors if present
if has_speech:
speech_dict = self.prepare_speech_inputs(
all_speech_inputs,
return_tensors=return_tensors,
)
batch_encoding["speech_tensors"] = speech_dict["padded_speeches"]
batch_encoding["speech_masks"] = speech_dict["speech_masks"]
else:
batch_encoding["speech_tensors"] = None
batch_encoding["speech_masks"] = None
return batch_encoding
def prepare_speech_inputs(
self,
speech_inputs: List[np.ndarray],
return_tensors: Optional[Union[str, TensorType]] = None,
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> Dict[str, Any]:
"""
Prepare speech inputs for model consumption.
Args:
speech_inputs: List of speech arrays
return_tensors: Output tensor type
device: Device to place tensors on
dtype: Data type for tensors
Returns:
Dictionary with padded_speeches and speech_masks
"""
if not speech_inputs:
return {"padded_speeches": None, "speech_masks": None}
# Calculate sequence lengths
vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) for s in speech_inputs]
# vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) if s.ndim == 1 else s.shape[0] for s in speech_inputs]
max_speech_length = max(s.shape[0] for s in speech_inputs)
# Pad speeches
if speech_inputs[0].ndim == 1:
padded_speeches = np.full((len(speech_inputs), max_speech_length), fill_value=0, dtype=np.float32)
else:
padded_speeches = np.full((len(speech_inputs), max_speech_length, speech_inputs[0].shape[-1]), fill_value=0, dtype=np.float32)
speech_masks = np.zeros((len(speech_inputs), max(vae_tok_seqlens)), dtype=np.bool_)
for i, (speech, vae_tok_length) in enumerate(zip(speech_inputs, vae_tok_seqlens)):
padded_speeches[i, :len(speech)] = speech
speech_masks[i, :vae_tok_length] = True
result = {
"padded_speeches": padded_speeches,
"speech_masks": speech_masks,
}
# Convert to tensors if requested
if return_tensors == "pt":
result["padded_speeches"] = torch.tensor(padded_speeches, device=device, dtype=dtype or torch.float32)
result["speech_masks"] = torch.tensor(speech_masks, device=device, dtype=torch.bool)
return result
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.batch_decode`].
Please refer to the docstring of this method for more information.
"""
return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.decode`].
Please refer to the docstring of this method for more information.
"""
return self.tokenizer.decode(*args, **kwargs)
@property
def model_input_names(self):
"""
Return the list of inputs accepted by the model.
"""
tokenizer_input_names = self.tokenizer.model_input_names
audio_processor_input_names = self.audio_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + audio_processor_input_names + ["speech_inputs", "speech_input_mask"]))
def save_audio(self,
audio: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]],
output_path: str = "output.wav",
sampling_rate: Optional[int] = None,
normalize: bool = False,
batch_prefix: str = "audio_",
) -> str:
"""
Save audio data to a file.
Args:
audio (Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]]):
The audio data to save. Can be a single tensor/array or a list of them.
output_path (str, optional): Path to save the audio file. Defaults to "output.wav".
sampling_rate (int, optional): Sampling rate for the audio. If None, uses the processor's default.
normalize (bool, optional): Whether to normalize the audio before saving. Defaults to False.
batch_prefix (str, optional): Prefix for batch audio files. Defaults to "audio_".
Returns:
str: The path to the saved audio file.
"""
return self.audio_processor.save_audio(audio, output_path=output_path, sampling_rate=sampling_rate, normalize=normalize, batch_prefix=batch_prefix)
__all__ = [
"VibeVoiceStreamingProcessor",
] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/processor/vibevoice_streaming_processor.py",
"license": "MIT License",
"lines": 355,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/processor/vibevoice_tokenizer_processor.py | """
Processor class for VibeVoice models.
"""
import os
import json
import warnings
from typing import List, Optional, Union, Dict, Any
import numpy as np
import torch
from transformers.feature_extraction_utils import FeatureExtractionMixin
from transformers.utils import logging
from .audio_utils import AudioNormalizer
logger = logging.get_logger(__name__)
# Change from ProcessorMixin to FeatureExtractionMixin which is designed for single components
class VibeVoiceTokenizerProcessor(FeatureExtractionMixin):
"""
Processor for VibeVoice acoustic tokenizer models.
This processor handles audio preprocessing for VibeVoice models, including:
- Audio format conversion (stereo to mono)
- Optional audio normalization
- Streaming support for infinite-length audio
Args:
sampling_rate (int, optional): Expected sampling rate. Defaults to 24000.
normalize_audio (bool, optional): Whether to normalize audio. Defaults to True.
target_dB_FS (float, optional): Target dB FS for normalization. Defaults to -25.
eps (float, optional): Small value for numerical stability. Defaults to 1e-6.
"""
model_input_names = ["input_features"]
def __init__(
self,
sampling_rate: int = 24000,
normalize_audio: bool = True,
target_dB_FS: float = -25,
eps: float = 1e-6,
**kwargs,
):
super().__init__(**kwargs)
self.sampling_rate = sampling_rate
self.normalize_audio = normalize_audio
# Initialize audio normalizer if needed
if self.normalize_audio:
self.normalizer = AudioNormalizer(target_dB_FS=target_dB_FS, eps=eps)
else:
self.normalizer = None
# Save config
self.feature_extractor_dict = {
"sampling_rate": sampling_rate,
"normalize_audio": normalize_audio,
"target_dB_FS": target_dB_FS,
"eps": eps,
}
def _ensure_mono(self, audio: np.ndarray) -> np.ndarray:
"""
Convert stereo audio to mono if needed.
Args:
audio (np.ndarray): Input audio array
Returns:
np.ndarray: Mono audio array
"""
if len(audio.shape) == 1:
return audio
elif len(audio.shape) == 2:
if audio.shape[0] == 2: # (2, time)
return np.mean(audio, axis=0)
elif audio.shape[1] == 2: # (time, 2)
return np.mean(audio, axis=1)
else:
# If one dimension is 1, squeeze it
if audio.shape[0] == 1:
return audio.squeeze(0)
elif audio.shape[1] == 1:
return audio.squeeze(1)
else:
raise ValueError(f"Unexpected audio shape: {audio.shape}")
else:
raise ValueError(f"Audio should be 1D or 2D, got shape: {audio.shape}")
def _process_single_audio(self, audio: Union[np.ndarray, List[float]]) -> np.ndarray:
"""
Process a single audio array.
Args:
audio: Single audio input
Returns:
np.ndarray: Processed audio
"""
# Convert to numpy array
if not isinstance(audio, np.ndarray):
audio = np.array(audio, dtype=np.float32)
else:
audio = audio.astype(np.float32)
# Ensure mono
audio = self._ensure_mono(audio)
# Normalize if requested
if self.normalize_audio and self.normalizer is not None:
audio = self.normalizer(audio)
return audio
def __call__(
self,
audio: Union[str, np.ndarray, List[float], List[np.ndarray], List[List[float]], List[str]] = None,
sampling_rate: Optional[int] = None,
return_tensors: Optional[str] = None,
**kwargs,
):
"""
Process audio for VibeVoice models.
Args:
audio: Audio input(s) to process. Can be:
- str: Path to audio file
- np.ndarray: Audio array
- List[float]: Audio as list of floats
- List[np.ndarray]: Batch of audio arrays
- List[str]: Batch of audio file paths
sampling_rate (int, optional): Sampling rate of the input audio
return_tensors (str, optional): Return format ('pt' for PyTorch, 'np' for NumPy)
Returns:
dict: Processed audio inputs with keys:
- input_features: Audio tensor(s) ready for the model
"""
if audio is None:
raise ValueError("Audio input is required")
# Validate sampling rate
if sampling_rate is not None and sampling_rate != self.sampling_rate:
logger.warning(
f"Input sampling rate ({sampling_rate}) differs from expected "
f"sampling rate ({self.sampling_rate}). Please resample your audio."
)
# Handle different input types
if isinstance(audio, str):
# Single audio file path
audio = self._load_audio_from_path(audio)
is_batched = False
elif isinstance(audio, list):
if len(audio) == 0:
raise ValueError("Empty audio list provided")
# Check if it's a list of file paths
if all(isinstance(item, str) for item in audio):
# Batch of audio file paths
audio = [self._load_audio_from_path(path) for path in audio]
is_batched = True
else:
# Check if it's batched audio arrays
is_batched = isinstance(audio[0], (np.ndarray, list))
else:
# Single audio array or list
is_batched = False
# Process audio
if is_batched:
processed_audio = [self._process_single_audio(a) for a in audio]
else:
processed_audio = [self._process_single_audio(audio)]
# Convert to tensors if requested
if return_tensors == "pt":
if len(processed_audio) == 1:
# Create a proper batch dimension (B, T)
input_features = torch.from_numpy(processed_audio[0]).unsqueeze(0).unsqueeze(1)
else:
# For batched input with different lengths, create a batch properly
input_features = torch.stack([torch.from_numpy(a) for a in processed_audio]).unsqueeze(1)
elif return_tensors == "np":
if len(processed_audio) == 1:
input_features = processed_audio[0][np.newaxis, np.newaxis, :]
else:
input_features = np.stack(processed_audio)[:, np.newaxis, :]
else:
input_features = processed_audio[0] if len(processed_audio) == 1 else processed_audio
outputs = {
"audio": input_features, # Use "audio" instead of "input_features"
}
return outputs
def _load_audio_from_path(self, audio_path: str) -> np.ndarray:
"""
Load audio from file path.
Args:
audio_path (str): Path to audio file
Returns:
np.ndarray: Loaded audio array
"""
# Get file extension to determine loading method
file_ext = os.path.splitext(audio_path)[1].lower()
if file_ext in ['.wav', '.mp3', '.flac', '.m4a', '.ogg']:
# Audio file - use librosa
import librosa
audio_array, sr = librosa.load(
audio_path,
sr=self.sampling_rate,
mono=True
)
return audio_array
elif file_ext == '.pt':
# PyTorch tensor file
audio_tensor = torch.load(audio_path, map_location='cpu', weights_only=True).squeeze()
if isinstance(audio_tensor, torch.Tensor):
audio_array = audio_tensor.numpy()
else:
audio_array = np.array(audio_tensor)
return audio_array.astype(np.float32)
elif file_ext == '.npy':
# NumPy file
audio_array = np.load(audio_path)
return audio_array.astype(np.float32)
else:
raise ValueError(
f"Unsupported file format: {file_ext}. "
f"Supported formats: .wav, .mp3, .flac, .m4a, .ogg, .pt, .npy, .npz"
)
def preprocess_audio(
self,
audio_path_or_array: Union[str, np.ndarray],
normalize: Optional[bool] = None,
) -> np.ndarray:
"""
Convenience method to preprocess audio from file path or array.
This method is kept for backward compatibility but __call__ is recommended.
Args:
audio_path_or_array: Path to audio file or numpy array
normalize: Whether to normalize (overrides default setting)
Returns:
np.ndarray: Preprocessed audio array
"""
if isinstance(audio_path_or_array, str):
audio_array = self._load_audio_from_path(audio_path_or_array)
else:
audio_array = np.array(audio_path_or_array, dtype=np.float32)
# Override normalization setting if specified
original_normalize = self.normalize_audio
if normalize is not None:
self.normalize_audio = normalize
try:
processed = self._process_single_audio(audio_array)
finally:
# Restore original setting
self.normalize_audio = original_normalize
return processed
# Override to_dict method for configuration saving
def to_dict(self) -> Dict[str, Any]:
"""
Convert the object to a dict containing all attributes needed for serialization.
"""
return self.feature_extractor_dict
def save_audio(
self,
audio: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]],
output_path: str = "output.wav",
sampling_rate: Optional[int] = None,
normalize: bool = False,
batch_prefix: str = "audio_",
):
"""
Save audio data to WAV file(s).
Args:
audio: Audio data to save. Can be:
- torch.Tensor: PyTorch tensor with shape (B, C, T) or (B, T) or (T)
- np.ndarray: NumPy array with shape (B, C, T) or (B, T) or (T)
- List of tensors or arrays
output_path: Path where to save the audio. If saving multiple files,
this is treated as a directory and individual files will be saved inside.
sampling_rate: Sampling rate for the saved audio. Defaults to the processor's rate.
normalize: Whether to normalize audio before saving.
batch_prefix: Prefix for batch files when saving multiple audios.
Returns:
List[str]: Paths to the saved audio files.
"""
if sampling_rate is None:
sampling_rate = self.sampling_rate
try:
import soundfile as sf
except ImportError:
raise ImportError(
"soundfile is required to save audio files. "
"Install it with: pip install soundfile"
)
# Ensure audio is in the right format
if isinstance(audio, torch.Tensor):
# Convert PyTorch tensor to numpy
audio_np = audio.float().detach().cpu().numpy()
elif isinstance(audio, np.ndarray):
audio_np = audio
elif isinstance(audio, list):
# Handle list of tensors or arrays
if all(isinstance(a, torch.Tensor) for a in audio):
audio_np = [a.float().detach().cpu().numpy() for a in audio]
else:
audio_np = audio
else:
raise ValueError(f"Unsupported audio type: {type(audio)}")
saved_paths = []
# Handle based on shape or type
if isinstance(audio_np, list):
# Multiple separate audios to save
output_dir = output_path
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Save each audio
for i, audio_item in enumerate(audio_np):
audio_item = self._prepare_audio_for_save(audio_item, normalize)
file_path = os.path.join(output_dir, f"{batch_prefix}{i}.wav")
sf.write(file_path, audio_item, sampling_rate)
saved_paths.append(file_path)
else:
# Handle different dimensions
if len(audio_np.shape) >= 3: # (B, C, T) or similar
# Get batch size
batch_size = audio_np.shape[0]
if batch_size > 1:
# Multiple audios in a batch
output_dir = output_path
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Save each audio in the batch
for i in range(batch_size):
# Extract single audio and remove channel dim if present
single_audio = audio_np[i]
if len(single_audio.shape) > 1:
if single_audio.shape[0] == 1: # (1, T)
single_audio = single_audio.squeeze(0)
single_audio = self._prepare_audio_for_save(single_audio, normalize)
file_path = os.path.join(output_dir, f"{batch_prefix}{i}.wav")
sf.write(file_path, single_audio, sampling_rate)
saved_paths.append(file_path)
else:
# Single audio with batch and channel dims
audio_item = audio_np.squeeze() # Remove batch and channel dimensions
audio_item = self._prepare_audio_for_save(audio_item, normalize)
sf.write(output_path, audio_item, sampling_rate)
saved_paths.append(output_path)
else:
# Single audio without batch dimension
audio_item = self._prepare_audio_for_save(audio_np, normalize)
sf.write(output_path, audio_item, sampling_rate)
saved_paths.append(output_path)
return saved_paths
def _prepare_audio_for_save(self, audio: np.ndarray, normalize: bool) -> np.ndarray:
"""
Prepare audio for saving by ensuring it's the right shape and optionally normalizing.
Args:
audio: Audio data as numpy array
normalize: Whether to normalize audio
Returns:
np.ndarray: Processed audio ready for saving
"""
# Ensure right dimensionality
if len(audio.shape) > 1 and audio.shape[0] == 1: # (1, T)
audio = audio.squeeze(0)
# Normalize if requested
if normalize:
max_val = np.abs(audio).max()
if max_val > 0:
audio = audio / max_val
return audio
__all__ = ["VibeVoiceTokenizerProcessor", "AudioNormalizer"] | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/processor/vibevoice_tokenizer_processor.py",
"license": "MIT License",
"lines": 349,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/VibeVoice:vibevoice/schedule/dpm_solver.py | # Copyright 2024 TSAIL Team and The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver
import math
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils import deprecate
from diffusers.utils.torch_utils import randn_tensor
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def betas_for_alpha_bar(
num_diffusion_timesteps,
max_beta=0.999,
alpha_transform_type="cosine",
):
"""
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
(1-beta) over time from t = [0,1].
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
to that part of the diffusion process.
Args:
num_diffusion_timesteps (`int`): the number of betas to produce.
max_beta (`float`): the maximum beta to use; use values lower than 1 to
prevent singularities.
alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
Choose from `cosine` or `exp`
Returns:
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(t):
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
# return math.cos(t * math.pi / 2 * 0.95) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(t):
return math.exp(t * -12.0)
elif alpha_transform_type == "cauchy":
# µ + γ tan (π (0.5 - x)) γ = 1, µ = 3
# alpha^2 = 1-1/(exp(λ)+1)
def alpha_bar_fn(t, gamma=1, mu=3):
snr = mu + gamma * math.tan(math.pi * (0.5 - t) * 0.9)
return 1 - 1 / (math.exp(snr) + 1.1)
elif alpha_transform_type == "laplace":
# µ − bsgn(0.5 − t) log(1 − 2|t − 0.5|) µ = 0, b = 1
def alpha_bar_fn(t, mu=0, b=1):
snr = mu - b * math.copysign(1, 0.5 - t) * math.log(1 - 2 * abs(t - 0.5) * 0.98)
return 1 - 1 / (math.exp(snr) + 1.02)
else:
raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
betas = []
for i in range(num_diffusion_timesteps):
t1 = i / num_diffusion_timesteps
t2 = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
return torch.tensor(betas, dtype=torch.float32)
# Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
def rescale_zero_terminal_snr(betas):
"""
Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
Args:
betas (`torch.Tensor`):
the betas that the scheduler is being initialized with.
Returns:
`torch.Tensor`: rescaled betas with zero terminal SNR
"""
# Convert betas to alphas_bar_sqrt
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
alphas_bar_sqrt = alphas_cumprod.sqrt()
# Store old values.
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
# Shift so the last timestep is zero.
alphas_bar_sqrt -= alphas_bar_sqrt_T
# Scale so the first timestep is back to the old value.
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
# Convert alphas_bar_sqrt to betas
alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
alphas = torch.cat([alphas_bar[0:1], alphas])
betas = 1 - alphas
return betas
class DPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
"""
`DPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
methods the library implements for all schedulers such as loading and saving.
Args:
num_train_timesteps (`int`, defaults to 1000):
The number of diffusion steps to train the model.
beta_start (`float`, defaults to 0.0001):
The starting `beta` value of inference.
beta_end (`float`, defaults to 0.02):
The final `beta` value.
beta_schedule (`str`, defaults to `"linear"`):
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
trained_betas (`np.ndarray`, *optional*):
Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
solver_order (`int`, defaults to 2):
The DPMSolver order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided
sampling, and `solver_order=3` for unconditional sampling.
prediction_type (`str`, defaults to `epsilon`, *optional*):
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
Video](https://imagen.research.google/video/paper.pdf) paper).
thresholding (`bool`, defaults to `False`):
Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
as Stable Diffusion.
dynamic_thresholding_ratio (`float`, defaults to 0.995):
The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
sample_max_value (`float`, defaults to 1.0):
The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
`algorithm_type="dpmsolver++"`.
algorithm_type (`str`, defaults to `dpmsolver++`):
Algorithm type for the solver; can be `dpmsolver`, `dpmsolver++`, `sde-dpmsolver` or `sde-dpmsolver++`. The
`dpmsolver` type implements the algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927)
paper, and the `dpmsolver++` type implements the algorithms in the
[DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or
`sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion.
solver_type (`str`, defaults to `midpoint`):
Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
lower_order_final (`bool`, defaults to `True`):
Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
euler_at_final (`bool`, defaults to `False`):
Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
steps, but sometimes may result in blurring.
use_karras_sigmas (`bool`, *optional*, defaults to `False`):
Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
the sigmas are determined according to a sequence of noise levels {σi}.
use_lu_lambdas (`bool`, *optional*, defaults to `False`):
Whether to use the uniform-logSNR for step sizes proposed by Lu's DPM-Solver in the noise schedule during
the sampling process. If `True`, the sigmas and time steps are determined according to a sequence of
`lambda(t)`.
final_sigmas_type (`str`, defaults to `"zero"`):
The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
lambda_min_clipped (`float`, defaults to `-inf`):
Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
cosine (`squaredcos_cap_v2`) noise schedule.
variance_type (`str`, *optional*):
Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
contains the predicted Gaussian variance.
timestep_spacing (`str`, defaults to `"linspace"`):
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
steps_offset (`int`, defaults to 0):
An offset added to the inference steps, as required by some model families.
rescale_betas_zero_snr (`bool`, defaults to `False`):
Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
dark samples instead of limiting it to samples with medium brightness. Loosely related to
[`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
"""
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
order = 1
@register_to_config
def __init__(
self,
num_train_timesteps: int = 1000,
beta_start: float = 0.0001,
beta_end: float = 0.02,
beta_schedule: str = "linear",
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
solver_order: int = 2,
prediction_type: str = "epsilon",
thresholding: bool = False,
dynamic_thresholding_ratio: float = 0.995,
sample_max_value: float = 1.0,
algorithm_type: str = "dpmsolver++",
solver_type: str = "midpoint",
lower_order_final: bool = True,
euler_at_final: bool = False,
use_karras_sigmas: Optional[bool] = False,
use_lu_lambdas: Optional[bool] = False,
final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
lambda_min_clipped: float = -float("inf"),
variance_type: Optional[str] = None,
timestep_spacing: str = "linspace",
steps_offset: int = 0,
rescale_betas_zero_snr: bool = False,
):
if algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
deprecation_message = f"algorithm_type {algorithm_type} is deprecated and will be removed in a future version. Choose from `dpmsolver++` or `sde-dpmsolver++` instead"
deprecate("algorithm_types dpmsolver and sde-dpmsolver", "1.0.0", deprecation_message)
if trained_betas is not None:
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
elif beta_schedule == "linear":
self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
elif beta_schedule == "squaredcos_cap_v2" or beta_schedule == "cosine":
# Glide cosine schedule
self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="cosine")
elif beta_schedule == "cauchy":
self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="cauchy")
elif beta_schedule == "laplace":
self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="laplace")
else:
raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
if rescale_betas_zero_snr:
self.betas = rescale_zero_terminal_snr(self.betas)
self.alphas = 1.0 - self.betas
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
if rescale_betas_zero_snr:
# Close to 0 without being 0 so first sigma is not inf
# FP16 smallest positive subnormal works well here
self.alphas_cumprod[-1] = 2**-24
# Currently we only support VP-type noise schedule
self.alpha_t = torch.sqrt(self.alphas_cumprod)
self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
self.sigmas = ((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5
# standard deviation of the initial noise distribution
self.init_noise_sigma = 1.0
# settings for DPM-Solver
if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
if algorithm_type == "deis":
self.register_to_config(algorithm_type="dpmsolver++")
else:
raise NotImplementedError(f"{algorithm_type} is not implemented for {self.__class__}")
if solver_type not in ["midpoint", "heun"]:
if solver_type in ["logrho", "bh1", "bh2"]:
self.register_to_config(solver_type="midpoint")
else:
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"] and final_sigmas_type == "zero":
raise ValueError(
f"`final_sigmas_type` {final_sigmas_type} is not supported for `algorithm_type` {algorithm_type}. Please choose `sigma_min` instead."
)
# setable values
self.num_inference_steps = None
timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
self.timesteps = torch.from_numpy(timesteps)
self.model_outputs = [None] * solver_order
self.lower_order_nums = 0
self._step_index = None
self._begin_index = None
self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
@property
def step_index(self):
"""
The index counter for current timestep. It will increase 1 after each scheduler step.
"""
return self._step_index
@property
def begin_index(self):
"""
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
"""
return self._begin_index
def set_begin_index(self, begin_index: int = 0):
"""
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
Args:
begin_index (`int`):
The begin index for the scheduler.
"""
self._begin_index = begin_index
def set_timesteps(
self,
num_inference_steps: int = None,
device: Union[str, torch.device] = None,
timesteps: Optional[List[int]] = None,
):
"""
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
Args:
num_inference_steps (`int`):
The number of diffusion steps used when generating samples with a pre-trained model.
device (`str` or `torch.device`, *optional*):
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
timesteps (`List[int]`, *optional*):
Custom timesteps used to support arbitrary timesteps schedule. If `None`, timesteps will be generated
based on the `timestep_spacing` attribute. If `timesteps` is passed, `num_inference_steps` and `sigmas`
must be `None`, and `timestep_spacing` attribute will be ignored.
"""
if num_inference_steps is None and timesteps is None:
raise ValueError("Must pass exactly one of `num_inference_steps` or `timesteps`.")
if num_inference_steps is not None and timesteps is not None:
raise ValueError("Can only pass one of `num_inference_steps` or `custom_timesteps`.")
if timesteps is not None and self.config.use_karras_sigmas:
raise ValueError("Cannot use `timesteps` with `config.use_karras_sigmas = True`")
if timesteps is not None and self.config.use_lu_lambdas:
raise ValueError("Cannot use `timesteps` with `config.use_lu_lambdas = True`")
if timesteps is not None:
timesteps = np.array(timesteps).astype(np.int64)
else:
# Clipping the minimum of all lambda(t) for numerical stability.
# This is critical for cosine (squaredcos_cap_v2) noise schedule.
clipped_idx = torch.searchsorted(torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped)
last_timestep = ((self.config.num_train_timesteps - clipped_idx).numpy()).item()
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
timesteps = (
np.linspace(0, last_timestep - 1, num_inference_steps + 1)
.round()[::-1][:-1]
.copy()
.astype(np.int64)
)
elif self.config.timestep_spacing == "leading":
step_ratio = last_timestep // (num_inference_steps + 1)
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
timesteps = (
(np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64)
)
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
step_ratio = self.config.num_train_timesteps / num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
timesteps = np.arange(last_timestep, 0, -step_ratio).round().copy().astype(np.int64)
timesteps -= 1
else:
raise ValueError(
f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
)
sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
log_sigmas = np.log(sigmas)
if self.config.use_karras_sigmas:
sigmas = np.flip(sigmas).copy()
sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
elif self.config.use_lu_lambdas:
lambdas = np.flip(log_sigmas.copy())
lambdas = self._convert_to_lu(in_lambdas=lambdas, num_inference_steps=num_inference_steps)
sigmas = np.exp(lambdas)
timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
else:
sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
if self.config.final_sigmas_type == "sigma_min":
sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5
elif self.config.final_sigmas_type == "zero":
sigma_last = 0
else:
raise ValueError(
f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
)
sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32)
self.sigmas = torch.from_numpy(sigmas)
self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64)
self.num_inference_steps = len(timesteps)
self.model_outputs = [
None,
] * self.config.solver_order
self.lower_order_nums = 0
# add an index counter for schedulers that allow duplicated timesteps
self._step_index = None
self._begin_index = None
self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
"""
"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
pixels from saturation at each step. We find that dynamic thresholding results in significantly better
photorealism as well as better image-text alignment, especially when using very large guidance weights."
https://arxiv.org/abs/2205.11487
"""
dtype = sample.dtype
batch_size, channels, *remaining_dims = sample.shape
if dtype not in (torch.float32, torch.float64):
sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
# Flatten sample for doing quantile calculation along each image
sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
abs_sample = sample.abs() # "a certain percentile absolute pixel value"
s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
s = torch.clamp(
s, min=1, max=self.config.sample_max_value
) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
sample = sample.reshape(batch_size, channels, *remaining_dims)
sample = sample.to(dtype)
return sample
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
def _sigma_to_t(self, sigma, log_sigmas):
# get log sigma
log_sigma = np.log(np.maximum(sigma, 1e-10))
# get distribution
dists = log_sigma - log_sigmas[:, np.newaxis]
# get sigmas range
low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
high_idx = low_idx + 1
low = log_sigmas[low_idx]
high = log_sigmas[high_idx]
# interpolate sigmas
w = (low - log_sigma) / (low - high)
w = np.clip(w, 0, 1)
# transform interpolation to time range
t = (1 - w) * low_idx + w * high_idx
t = t.reshape(sigma.shape)
return t
def _sigma_to_alpha_sigma_t(self, sigma):
alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
sigma_t = sigma * alpha_t
return alpha_t, sigma_t
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
def _convert_to_karras(self, in_sigmas: torch.Tensor, num_inference_steps) -> torch.Tensor:
"""Constructs the noise schedule of Karras et al. (2022)."""
# Hack to make sure that other schedulers which copy this function don't break
# TODO: Add this logic to the other schedulers
if hasattr(self.config, "sigma_min"):
sigma_min = self.config.sigma_min
else:
sigma_min = None
if hasattr(self.config, "sigma_max"):
sigma_max = self.config.sigma_max
else:
sigma_max = None
sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
rho = 7.0 # 7.0 is the value used in the paper
ramp = np.linspace(0, 1, num_inference_steps)
min_inv_rho = sigma_min ** (1 / rho)
max_inv_rho = sigma_max ** (1 / rho)
sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return sigmas
def _convert_to_lu(self, in_lambdas: torch.Tensor, num_inference_steps) -> torch.Tensor:
"""Constructs the noise schedule of Lu et al. (2022)."""
lambda_min: float = in_lambdas[-1].item()
lambda_max: float = in_lambdas[0].item()
rho = 1.0 # 1.0 is the value used in the paper
ramp = np.linspace(0, 1, num_inference_steps)
min_inv_rho = lambda_min ** (1 / rho)
max_inv_rho = lambda_max ** (1 / rho)
lambdas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return lambdas
def convert_model_output(
self,
model_output: torch.Tensor,
*args,
sample: torch.Tensor = None,
**kwargs,
) -> torch.Tensor:
"""
Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
integral of the data prediction model.
<Tip>
The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
prediction and data prediction models.
</Tip>
Args:
model_output (`torch.Tensor`):
The direct output from the learned diffusion model.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusion process.
Returns:
`torch.Tensor`:
The converted model output.
"""
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
if sample is None:
if len(args) > 1:
sample = args[1]
else:
raise ValueError("missing `sample` as a required keyward argument")
if timestep is not None:
deprecate(
"timesteps",
"1.0.0",
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
# DPM-Solver++ needs to solve an integral of the data prediction model.
if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
if self.config.prediction_type == "epsilon":
# DPM-Solver and DPM-Solver++ only need the "mean" output.
if self.config.variance_type in ["learned", "learned_range"]:
model_output = model_output[:, :3]
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
x0_pred = (sample - sigma_t * model_output) / alpha_t
elif self.config.prediction_type == "sample":
x0_pred = model_output
elif self.config.prediction_type == "v_prediction":
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
x0_pred = alpha_t * sample - sigma_t * model_output
else:
raise ValueError(
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
" `v_prediction` for the DPMSolverMultistepScheduler."
)
if self.config.thresholding:
x0_pred = self._threshold_sample(x0_pred)
return x0_pred
# DPM-Solver needs to solve an integral of the noise prediction model.
elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
if self.config.prediction_type == "epsilon":
# DPM-Solver and DPM-Solver++ only need the "mean" output.
if self.config.variance_type in ["learned", "learned_range"]:
epsilon = model_output[:, :3]
else:
epsilon = model_output
elif self.config.prediction_type == "sample":
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
epsilon = (sample - alpha_t * model_output) / sigma_t
elif self.config.prediction_type == "v_prediction":
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
epsilon = alpha_t * model_output + sigma_t * sample
else:
raise ValueError(
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
" `v_prediction` for the DPMSolverMultistepScheduler."
)
if self.config.thresholding:
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
x0_pred = (sample - sigma_t * epsilon) / alpha_t
x0_pred = self._threshold_sample(x0_pred)
epsilon = (sample - alpha_t * x0_pred) / sigma_t
return epsilon
def dpm_solver_first_order_update(
self,
model_output: torch.Tensor,
*args,
sample: torch.Tensor = None,
noise: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
"""
One step for the first-order DPMSolver (equivalent to DDIM).
Args:
model_output (`torch.Tensor`):
The direct output from the learned diffusion model.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusion process.
Returns:
`torch.Tensor`:
The sample tensor at the previous timestep.
"""
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
if len(args) > 2:
sample = args[2]
else:
raise ValueError(" missing `sample` as a required keyward argument")
if timestep is not None:
deprecate(
"timesteps",
"1.0.0",
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
if prev_timestep is not None:
deprecate(
"prev_timestep",
"1.0.0",
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
h = lambda_t - lambda_s
if self.config.algorithm_type == "dpmsolver++":
x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
elif self.config.algorithm_type == "dpmsolver":
x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output
elif self.config.algorithm_type == "sde-dpmsolver++":
assert noise is not None
x_t = (
(sigma_t / sigma_s * torch.exp(-h)) * sample
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
)
elif self.config.algorithm_type == "sde-dpmsolver":
assert noise is not None
x_t = (
(alpha_t / alpha_s) * sample
- 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
)
return x_t
def multistep_dpm_solver_second_order_update(
self,
model_output_list: List[torch.Tensor],
*args,
sample: torch.Tensor = None,
noise: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
"""
One step for the second-order multistep DPMSolver.
Args:
model_output_list (`List[torch.Tensor]`):
The direct outputs from learned diffusion model at current and latter timesteps.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusion process.
Returns:
`torch.Tensor`:
The sample tensor at the previous timestep.
"""
timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
if len(args) > 2:
sample = args[2]
else:
raise ValueError(" missing `sample` as a required keyward argument")
if timestep_list is not None:
deprecate(
"timestep_list",
"1.0.0",
"Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
if prev_timestep is not None:
deprecate(
"prev_timestep",
"1.0.0",
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
sigma_t, sigma_s0, sigma_s1 = (
self.sigmas[self.step_index + 1],
self.sigmas[self.step_index],
self.sigmas[self.step_index - 1],
)
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
m0, m1 = model_output_list[-1], model_output_list[-2]
h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
r0 = h_0 / h
D0, D1 = m0, (1.0 / r0) * (m0 - m1)
if self.config.algorithm_type == "dpmsolver++":
# See https://arxiv.org/abs/2211.01095 for detailed derivations
if self.config.solver_type == "midpoint":
x_t = (
(sigma_t / sigma_s0) * sample
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
- 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
)
elif self.config.solver_type == "heun":
x_t = (
(sigma_t / sigma_s0) * sample
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
)
elif self.config.algorithm_type == "dpmsolver":
# See https://arxiv.org/abs/2206.00927 for detailed derivations
if self.config.solver_type == "midpoint":
x_t = (
(alpha_t / alpha_s0) * sample
- (sigma_t * (torch.exp(h) - 1.0)) * D0
- 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
)
elif self.config.solver_type == "heun":
x_t = (
(alpha_t / alpha_s0) * sample
- (sigma_t * (torch.exp(h) - 1.0)) * D0
- (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
)
elif self.config.algorithm_type == "sde-dpmsolver++":
assert noise is not None
if self.config.solver_type == "midpoint":
x_t = (
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
+ 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
)
elif self.config.solver_type == "heun":
x_t = (
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
+ (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
)
elif self.config.algorithm_type == "sde-dpmsolver":
assert noise is not None
if self.config.solver_type == "midpoint":
x_t = (
(alpha_t / alpha_s0) * sample
- 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
- (sigma_t * (torch.exp(h) - 1.0)) * D1
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
)
elif self.config.solver_type == "heun":
x_t = (
(alpha_t / alpha_s0) * sample
- 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
- 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
)
return x_t
def multistep_dpm_solver_third_order_update(
self,
model_output_list: List[torch.Tensor],
*args,
sample: torch.Tensor = None,
**kwargs,
) -> torch.Tensor:
"""
One step for the third-order multistep DPMSolver.
Args:
model_output_list (`List[torch.Tensor]`):
The direct outputs from learned diffusion model at current and latter timesteps.
sample (`torch.Tensor`):
A current instance of a sample created by diffusion process.
Returns:
`torch.Tensor`:
The sample tensor at the previous timestep.
"""
timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
if len(args) > 2:
sample = args[2]
else:
raise ValueError(" missing`sample` as a required keyward argument")
if timestep_list is not None:
deprecate(
"timestep_list",
"1.0.0",
"Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
if prev_timestep is not None:
deprecate(
"prev_timestep",
"1.0.0",
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
self.sigmas[self.step_index + 1],
self.sigmas[self.step_index],
self.sigmas[self.step_index - 1],
self.sigmas[self.step_index - 2],
)
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
r0, r1 = h_0 / h, h_1 / h
D0 = m0
D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
if self.config.algorithm_type == "dpmsolver++":
# See https://arxiv.org/abs/2206.00927 for detailed derivations
x_t = (
(sigma_t / sigma_s0) * sample
- (alpha_t * (torch.exp(-h) - 1.0)) * D0
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
- (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
)
elif self.config.algorithm_type == "dpmsolver":
# See https://arxiv.org/abs/2206.00927 for detailed derivations
x_t = (
(alpha_t / alpha_s0) * sample
- (sigma_t * (torch.exp(h) - 1.0)) * D0
- (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
- (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
)
return x_t
def index_for_timestep(self, timestep, schedule_timesteps=None):
if schedule_timesteps is None:
schedule_timesteps = self.timesteps
index_candidates = (schedule_timesteps == timestep).nonzero()
if len(index_candidates) == 0:
step_index = len(self.timesteps) - 1
# The sigma index that is taken for the **very** first `step`
# is always the second index (or the last index if there is only 1)
# This way we can ensure we don't accidentally skip a sigma in
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
elif len(index_candidates) > 1:
step_index = index_candidates[1].item()
else:
step_index = index_candidates[0].item()
return step_index
def _init_step_index(self, timestep):
"""
Initialize the step_index counter for the scheduler.
"""
if self.begin_index is None:
if isinstance(timestep, torch.Tensor):
timestep = timestep.to(self.timesteps.device)
self._step_index = self.index_for_timestep(timestep)
else:
self._step_index = self._begin_index
def step(
self,
model_output: torch.Tensor,
timestep: int,
sample: torch.Tensor,
generator=None,
variance_noise: Optional[torch.Tensor] = None,
return_dict: bool = True,
) -> Union[SchedulerOutput, Tuple]:
"""
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
the multistep DPMSolver.
Args:
model_output (`torch.Tensor`):
The direct output from learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusion process.
generator (`torch.Generator`, *optional*):
A random number generator.
variance_noise (`torch.Tensor`):
Alternative to generating noise with `generator` by directly providing the noise for the variance
itself. Useful for methods such as [`LEdits++`].
return_dict (`bool`):
Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
Returns:
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
tuple is returned where the first element is the sample tensor.
"""
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
)
if self.step_index is None:
self._init_step_index(timestep)
# Improve numerical stability for small number of steps
lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
self.config.euler_at_final
or (self.config.lower_order_final and len(self.timesteps) < 15)
or self.config.final_sigmas_type == "zero"
)
lower_order_second = (
(self.step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
)
model_output = self.convert_model_output(model_output, sample=sample)
for i in range(self.config.solver_order - 1):
self.model_outputs[i] = self.model_outputs[i + 1]
self.model_outputs[-1] = model_output
# Upcast to avoid precision issues when computing prev_sample
sample = sample.to(torch.float32)
if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"] and variance_noise is None:
noise = randn_tensor(
model_output.shape, generator=generator, device=model_output.device, dtype=torch.float32
)
elif self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
noise = variance_noise.to(device=model_output.device, dtype=torch.float32)
else:
noise = None
if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
prev_sample = self.dpm_solver_first_order_update(model_output, sample=sample, noise=noise)
elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
prev_sample = self.multistep_dpm_solver_second_order_update(self.model_outputs, sample=sample, noise=noise)
else:
prev_sample = self.multistep_dpm_solver_third_order_update(self.model_outputs, sample=sample)
if self.lower_order_nums < self.config.solver_order:
self.lower_order_nums += 1
# Cast sample back to expected dtype
prev_sample = prev_sample.to(model_output.dtype)
# upon completion increase step index by one
self._step_index += 1
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=prev_sample)
def add_noise(
self,
original_samples: torch.Tensor,
noise: torch.Tensor,
timesteps: torch.IntTensor,
) -> torch.Tensor:
# Make sure sigmas and timesteps have the same device and dtype as original_samples
# alpha_t = self.alpha_t.to(device=original_samples.device, dtype=original_samples.dtype)
# sigma_t = self.sigma_t.to(device=original_samples.device, dtype=original_samples.dtype)
alpha_t = self.alpha_t.to(original_samples.device).to(original_samples.dtype)
sigma_t = self.sigma_t.to(original_samples.device).to(original_samples.dtype)
timesteps = timesteps.to(original_samples.device)
alpha_t = alpha_t[timesteps].flatten()
while len(alpha_t.shape) < len(original_samples.shape):
alpha_t = alpha_t.unsqueeze(-1)
sigma_t = sigma_t[timesteps].flatten()
while len(sigma_t.shape) < len(original_samples.shape):
sigma_t = sigma_t.unsqueeze(-1)
noisy_samples = alpha_t * original_samples + sigma_t * noise
return noisy_samples
def get_velocity(self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.IntTensor) -> torch.Tensor:
# alpha_t = self.alpha_t.to(device=original_samples.device, dtype=original_samples.dtype)
# sigma_t = self.sigma_t.to(device=original_samples.device, dtype=original_samples.dtype)
alpha_t = self.alpha_t.to(original_samples.device).to(original_samples.dtype)
sigma_t = self.sigma_t.to(original_samples.device).to(original_samples.dtype)
timesteps = timesteps.to(original_samples.device)
alpha_t = alpha_t[timesteps].flatten()
while len(alpha_t.shape) < len(original_samples.shape):
alpha_t = alpha_t.unsqueeze(-1)
sigma_t = sigma_t[timesteps].flatten()
while len(sigma_t.shape) < len(original_samples.shape):
sigma_t = sigma_t.unsqueeze(-1)
velocity = alpha_t * noise - sigma_t * original_samples
return velocity
def __len__(self):
return self.config.num_train_timesteps | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/schedule/dpm_solver.py",
"license": "MIT License",
"lines": 920,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/VibeVoice:vibevoice/schedule/timestep_sampler.py | import math
import torch
class UniformSampler:
def __init__(self, timesteps = 1000):
self.timesteps = timesteps
def sample(self, batch_size, device):
return torch.randint(0, self.timesteps, (batch_size,), device=device)
class LogitNormalSampler:
def __init__(self, timesteps = 1000, m = 0, s = 1):
self.timesteps = timesteps
timesteps = torch.linspace(0, 1, timesteps)
logit = torch.log(timesteps / (1 - timesteps))
self.prob = torch.exp(-0.5 * (logit - m) ** 2 / s ** 2) / (s * math.sqrt(2 * math.pi))
def sample(self, batch_size, device):
return torch.multinomial(self.prob, batch_size, replacement=True).to(device)
| {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/schedule/timestep_sampler.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
microsoft/VibeVoice:vibevoice/scripts/convert_nnscaler_checkpoint_to_transformers.py | #!/usr/bin/env python
# coding=utf-8
import argparse
import json
import os
from pathlib import Path
import re
import torch
from typing import Dict, List, Tuple
from vibevoice.modular.configuration_vibevoice import (
VibeVoiceConfig
)
from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration
from transformers.utils import logging
logger = logging.get_logger(__name__)
def convert_vibevoice_nnscaler_checkpoint_to_hf(
checkpoint_path: str,
pytorch_dump_folder_path: str,
config_path: str = None,
):
"""
Convert a nnscaler VibeVoice checkpoint to HuggingFace format.
Supports both regular checkpoints and tensor parallel checkpoints.
"""
# Load regular checkpoint
logger.info(f"Loading regular checkpoint from {checkpoint_path}")
checkpoint = torch.load(checkpoint_path, map_location="cpu") # ['model', 'optimizer', 'lr_scheduler', 'train_status', 'train_args', 'rng_states', 'nnscaler', 'dataloader']
# config = checkpoint['train_args']
init_config_name = checkpoint['train_args']['vars']['model_args']['config_path']['relative_path']
pretrained_name = checkpoint['train_args']['vars']['data_args']['tokenizer_path']
init_config_path = Path(__file__).parent.parent / 'configs' / init_config_name.split('/')[-1]
if init_config_path.exists():
logger.info(f"Loading initial config from {init_config_path}")
with open(init_config_path, 'r') as f:
init_config = json.load(f)
else:
raise FileNotFoundError(f"Initial config file {init_config_path} not found. Please provide a valid path.")
tie_word_embeddings = init_config['decoder_config'].get('tie_word_embeddings', True)
logger.info(f"Tie word embeddings: {tie_word_embeddings}")
init_config['decoder_config']['use_cache'] = True
config = VibeVoiceConfig(**init_config, tie_word_embeddings=tie_word_embeddings)
# # Extract the model state dict
model_state_dict = {k.replace('model.model.', 'model.'): v for k, v in checkpoint["model"].items() if k.startswith('model.model.')}
if not tie_word_embeddings and 'model.lm_head.weight' in checkpoint["model"].keys():
# If not tying weights, we need to add the lm_head weight separately
model_state_dict['lm_head.weight'] = checkpoint["model"]['model.lm_head.weight']
# Override with provided config if available
if config_path:
logger.info(f"Loading config from {config_path}")
with open(config_path, 'r') as f:
config_dict = json.load(f)
config = VibeVoiceConfig.from_dict(config_dict)
# Set the default dtype to bfloat16 before creating the model
original_dtype = torch.get_default_dtype()
torch.set_default_dtype(torch.bfloat16)
# Create the HuggingFace model
logger.info("Creating HuggingFace VibeVoiceForConditionalGeneration model")
model = VibeVoiceForConditionalGeneration(config)
# Restore original dtype
torch.set_default_dtype(original_dtype)
# Load the state dict
logger.info("Loading weights into model")
missing_keys, unexpected_keys = model.load_state_dict(model_state_dict, strict=False)
if missing_keys:
logger.warning(f"Missing keys: {missing_keys}")
if unexpected_keys:
logger.warning(f"Unexpected keys: {unexpected_keys}")
# Create output directory
os.makedirs(pytorch_dump_folder_path, exist_ok=True)
# Save the model and config
logger.info(f"Saving model to {pytorch_dump_folder_path}")
# Save config
config.save_pretrained(pytorch_dump_folder_path)
# Save VibeVoiceProcessor configuration
logger.info("Saving VibeVoiceProcessor configuration")
processor_config = {
"processor_class": "VibeVoiceProcessor",
"speech_tok_compress_ratio": 3200,
"db_normalize": True,
# Audio processor configuration
"audio_processor": {
"feature_extractor_type": "VibeVoiceTokenizerProcessor",
"sampling_rate": 24000,
"normalize_audio": True,
"target_dB_FS": -25,
"eps": 1e-6,
},
"language_model_pretrained_name": pretrained_name,
}
processor_config_path = os.path.join(pytorch_dump_folder_path, "preprocessor_config.json")
with open(processor_config_path, 'w') as f:
json.dump(processor_config, f, indent=2)
logger.info(f"Saved processor config to {processor_config_path}")
# Save model with sharding
# save_pretrained handles tied weights automatically
logger.info("Saving model weights with sharding...")
model.save_pretrained(
pytorch_dump_folder_path,
max_shard_size="2GB", # Set maximum size for each shard
safe_serialization=True # Ensure saving in .safetensors format
)
logger.info(f"Model weights saved to {pytorch_dump_folder_path}")
logger.info("Conversion complete!")
# Verify the saved model can be loaded
logger.info("Verifying saved model...")
loaded_model = VibeVoiceForConditionalGeneration.from_pretrained(pytorch_dump_folder_path)
logger.info("Model successfully loaded from saved checkpoint!")
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--nnscaler_checkpoint_path",
type=str,
required=True,
help="Path to the fairseq checkpoint (.pt file). For tensor parallel checkpoints, "
"provide any one of the part files (e.g., checkpoint_1_5000-model_part-0.pt), "
"and the script will automatically detect and merge all parts.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
type=str,
required=True,
help="Path to the output PyTorch model directory",
)
parser.add_argument(
"--config_path",
type=str,
default=None,
help="Optional path to a config JSON file to override extracted config",
)
args = parser.parse_args()
convert_vibevoice_nnscaler_checkpoint_to_hf(
args.nnscaler_checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
)
if __name__ == "__main__":
main() | {
"repo_id": "microsoft/VibeVoice",
"file_path": "vibevoice/scripts/convert_nnscaler_checkpoint_to_transformers.py",
"license": "MIT License",
"lines": 137,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
microsoft/graphrag:packages/graphrag/graphrag/index/operations/extract_graph/utils.py | # Copyright (C) 2026 Microsoft Corporation.
# Licensed under the MIT License
"""Utility functions for graph extraction operations."""
import logging
import pandas as pd
logger = logging.getLogger(__name__)
def filter_orphan_relationships(
relationships: pd.DataFrame,
entities: pd.DataFrame,
) -> pd.DataFrame:
"""Remove relationships whose source or target has no entity entry.
After LLM graph extraction, the model may hallucinate entity
names in relationships that have no corresponding entity row.
This function drops those dangling references so downstream
processing never encounters broken graph edges.
Parameters
----------
relationships:
Merged relationship DataFrame with at least ``source``
and ``target`` columns.
entities:
Merged entity DataFrame with at least a ``title`` column.
Returns
-------
pd.DataFrame
Relationships filtered to only those whose ``source``
and ``target`` both appear in ``entities["title"]``.
"""
if relationships.empty or entities.empty:
return relationships.iloc[0:0].reset_index(drop=True)
entity_titles = set(entities["title"])
before_count = len(relationships)
mask = relationships["source"].isin(entity_titles) & relationships["target"].isin(
entity_titles
)
filtered = relationships[mask].reset_index(drop=True)
dropped = before_count - len(filtered)
if dropped > 0:
logger.warning(
"Dropped %d relationship(s) referencing non-existent entities.",
dropped,
)
return filtered
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/index/operations/extract_graph/utils.py",
"license": "MIT License",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/indexing/operations/test_extract_graph.py | # Copyright (C) 2026 Microsoft Corporation.
# Licensed under the MIT License
"""Tests for extract_graph merge and orphan-filtering operations.
Validates that _merge_entities, _merge_relationships, and
filter_orphan_relationships correctly aggregate per-text-unit
extraction results and remove relationships whose source or
target has no corresponding entity.
"""
import pandas as pd
from graphrag.index.operations.extract_graph.extract_graph import (
_merge_entities,
_merge_relationships,
)
from graphrag.index.operations.extract_graph.utils import (
filter_orphan_relationships,
)
def _entity_row(
title: str,
entity_type: str = "THING",
description: str = "desc",
source_id: str = "tu1",
) -> dict:
"""Build a single raw entity row as produced by the graph extractor."""
return {
"title": title,
"type": entity_type,
"description": description,
"source_id": source_id,
}
def _relationship_row(
source: str,
target: str,
weight: float = 1.0,
description: str = "desc",
source_id: str = "tu1",
) -> dict:
"""Build a single raw relationship row as produced by the graph extractor."""
return {
"source": source,
"target": target,
"weight": weight,
"description": description,
"source_id": source_id,
}
class TestMergeEntities:
"""Tests for the _merge_entities aggregation helper."""
def test_groups_by_title_and_type(self):
"""Entities with the same title+type merge into one row."""
df1 = pd.DataFrame([_entity_row("A", "PERSON")])
df2 = pd.DataFrame([_entity_row("A", "PERSON", source_id="tu2")])
merged = _merge_entities([df1, df2])
assert len(merged) == 1
assert merged.iloc[0]["title"] == "A"
assert merged.iloc[0]["frequency"] == 2
def test_different_types_stay_separate(self):
"""Same title but different type should not merge."""
df = pd.DataFrame([
_entity_row("A", "PERSON"),
_entity_row("A", "ORG"),
])
merged = _merge_entities([df])
assert len(merged) == 2
def test_empty_input(self):
"""Empty entity list should produce an empty DataFrame."""
df = pd.DataFrame(columns=["title", "type", "description", "source_id"])
merged = _merge_entities([df])
assert len(merged) == 0
class TestMergeRelationships:
"""Tests for the _merge_relationships aggregation helper."""
def test_groups_by_source_target(self):
"""Relationships with same source+target merge and sum weight."""
df1 = pd.DataFrame([_relationship_row("A", "B", weight=2.0)])
df2 = pd.DataFrame([_relationship_row("A", "B", weight=3.0)])
merged = _merge_relationships([df1, df2])
assert len(merged) == 1
assert merged.iloc[0]["weight"] == 5.0
def test_distinct_pairs_stay_separate(self):
"""Different source-target pairs remain separate rows."""
df = pd.DataFrame([
_relationship_row("A", "B"),
_relationship_row("B", "C"),
])
merged = _merge_relationships([df])
assert len(merged) == 2
def test_empty_input(self):
"""Empty relationship list should produce an empty DataFrame."""
df = pd.DataFrame(
columns=["source", "target", "weight", "description", "source_id"]
)
merged = _merge_relationships([df])
assert len(merged) == 0
class TestFilterOrphanRelationships:
"""Tests for orphan relationship filtering.
After LLM graph extraction, relationships may reference entity
names that have no corresponding entity row. These must be
removed before downstream processing.
"""
def test_all_valid_relationships_kept(self):
"""Relationships whose endpoints all exist should be retained."""
entities = pd.DataFrame([
_entity_row("A"),
_entity_row("B"),
_entity_row("C"),
])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("A", "B"),
_relationship_row("B", "C"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 2
def test_removes_relationship_with_missing_source(self):
"""Relationship whose source has no entity entry is dropped."""
entities = pd.DataFrame([_entity_row("B")])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("PHANTOM", "B"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_removes_relationship_with_missing_target(self):
"""Relationship whose target has no entity entry is dropped."""
entities = pd.DataFrame([_entity_row("A")])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("A", "PHANTOM"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_removes_relationship_with_both_missing(self):
"""Relationship where both endpoints are missing is dropped."""
entities = pd.DataFrame([_entity_row("A")])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("GHOST_1", "GHOST_2"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_keeps_valid_drops_orphan_mixed(self):
"""Valid and orphaned relationships coexist; only valid survive."""
entities = pd.DataFrame([
_entity_row("A"),
_entity_row("B"),
])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("A", "B"),
_relationship_row("A", "PHANTOM"),
_relationship_row("PHANTOM", "B"),
_relationship_row("GHOST_1", "GHOST_2"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 1
assert filtered.iloc[0]["source"] == "A"
assert filtered.iloc[0]["target"] == "B"
def test_empty_entities_drops_all_relationships(self):
"""If there are no entities, all relationships are orphaned."""
entities = pd.DataFrame(columns=["title", "type", "description", "source_id"])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("A", "B"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_empty_relationships_returns_empty(self):
"""If there are no relationships, result is empty DataFrame."""
entities = pd.DataFrame([_entity_row("A")])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame(
columns=["source", "target", "weight", "description", "source_id"]
)
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_preserves_all_columns(self):
"""Filtered DataFrame retains all original columns."""
entities = pd.DataFrame([
_entity_row("A"),
_entity_row("B"),
])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("A", "B", weight=5.0, description="linked"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert set(filtered.columns) == set(merged_rels.columns)
assert filtered.iloc[0]["weight"] == 5.0
assert filtered.iloc[0]["description"] == ["linked"]
def test_multi_text_unit_orphan(self):
"""Orphan detected across multiple text units after merge."""
df1 = pd.DataFrame([
_entity_row("A", source_id="tu1"),
_relationship_row("A", "HALLUCINATED", source_id="tu1"),
])
df2 = pd.DataFrame([
_entity_row("A", source_id="tu2"),
_relationship_row("A", "HALLUCINATED", source_id="tu2"),
])
entity_dfs = [
df1[["title", "type", "description", "source_id"]],
df2[["title", "type", "description", "source_id"]],
]
rel_dfs = [
df1[["source", "target", "weight", "description", "source_id"]],
df2[["source", "target", "weight", "description", "source_id"]],
]
merged_entities = _merge_entities(entity_dfs)
merged_rels = _merge_relationships(rel_dfs)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 0
def test_resets_index_after_filter(self):
"""Filtered DataFrame should have a clean 0-based index."""
entities = pd.DataFrame([
_entity_row("A"),
_entity_row("B"),
_entity_row("C"),
])
merged_entities = _merge_entities([entities])
relationships = pd.DataFrame([
_relationship_row("PHANTOM", "B"),
_relationship_row("A", "B"),
_relationship_row("A", "PHANTOM"),
_relationship_row("B", "C"),
])
merged_rels = _merge_relationships([relationships])
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert list(filtered.index) == list(range(len(filtered)))
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/operations/test_extract_graph.py",
"license": "MIT License",
"lines": 234,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/indexing/update/test_update_relationships.py | # Copyright (C) 2026 Microsoft Corporation.
# Licensed under the MIT License
"""Tests for incremental update merge operations.
Covers _update_and_merge_relationships and orphan-filtering
in the update pipeline, where old finalized data is merged
with delta data from a new indexing run.
"""
import pandas as pd
from graphrag.index.operations.extract_graph.utils import (
filter_orphan_relationships,
)
from graphrag.index.update.relationships import (
_update_and_merge_relationships,
)
def _finalized_entity_row(
title: str,
entity_id: str = "e1",
human_readable_id: int = 0,
entity_type: str = "THING",
description: str = "desc",
frequency: int = 1,
degree: int = 1,
) -> dict:
"""Build a finalized entity row matching ENTITIES_FINAL_COLUMNS shape."""
return {
"id": entity_id,
"human_readable_id": human_readable_id,
"title": title,
"type": entity_type,
"description": description,
"text_unit_ids": ["tu1"],
"frequency": frequency,
"degree": degree,
}
def _finalized_relationship_row(
source: str,
target: str,
relationship_id: str = "r1",
human_readable_id: int = 0,
weight: float = 1.0,
description: str = "desc",
combined_degree: int = 2,
) -> dict:
"""Build a finalized relationship row matching RELATIONSHIPS_FINAL_COLUMNS."""
return {
"id": relationship_id,
"human_readable_id": human_readable_id,
"source": source,
"target": target,
"description": description,
"weight": weight,
"combined_degree": combined_degree,
"text_unit_ids": ["tu1"],
}
class TestUpdateAndMergeRelationships:
"""Tests for _update_and_merge_relationships."""
def test_merges_old_and_delta(self):
"""Old and delta relationships with distinct pairs both appear."""
old = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r1"),
])
delta = pd.DataFrame([
_finalized_relationship_row("C", "D", relationship_id="r2"),
])
merged = _update_and_merge_relationships(old, delta)
pairs = set(zip(merged["source"], merged["target"], strict=True))
assert ("A", "B") in pairs
assert ("C", "D") in pairs
assert len(merged) == 2
def test_overlapping_pairs_aggregate(self):
"""Same source+target in old and delta get grouped together."""
old = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r1", weight=2.0),
])
delta = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r2", weight=4.0),
])
merged = _update_and_merge_relationships(old, delta)
assert len(merged) == 1
assert merged.iloc[0]["weight"] == 3.0 # mean of 2.0 and 4.0
def test_human_readable_ids_incremented(self):
"""Delta human_readable_ids should be offset by old max + 1."""
old = pd.DataFrame([
_finalized_relationship_row("A", "B", human_readable_id=5),
])
delta = pd.DataFrame([
_finalized_relationship_row("C", "D", human_readable_id=0),
])
merged = _update_and_merge_relationships(old, delta)
ids = set(merged["human_readable_id"])
assert len(ids) == 2
class TestUpdatePathOrphanFiltering:
"""Tests that orphan relationships are caught in the update path.
The update pipeline merges old finalized entities with delta
entities, then merges old finalized relationships with delta
relationships. Delta relationships from LLM extraction may
reference hallucinated entity names that don't exist in the
merged entity set.
"""
def test_delta_introduces_orphan_source(self):
"""Delta relationship with hallucinated source is filtered out."""
merged_entities = pd.DataFrame([
_finalized_entity_row("A", entity_id="e1"),
_finalized_entity_row("B", entity_id="e2"),
])
old_rels = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r1"),
])
delta_rels = pd.DataFrame([
_finalized_relationship_row("HALLUCINATED", "B", relationship_id="r2"),
])
merged_rels = _update_and_merge_relationships(old_rels, delta_rels)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 1
assert filtered.iloc[0]["source"] == "A"
def test_delta_introduces_orphan_target(self):
"""Delta relationship with hallucinated target is filtered out."""
merged_entities = pd.DataFrame([
_finalized_entity_row("A", entity_id="e1"),
_finalized_entity_row("B", entity_id="e2"),
])
old_rels = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r1"),
])
delta_rels = pd.DataFrame([
_finalized_relationship_row("A", "HALLUCINATED", relationship_id="r2"),
])
merged_rels = _update_and_merge_relationships(old_rels, delta_rels)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 1
assert filtered.iloc[0]["target"] == "B"
def test_delta_introduces_orphan_both_endpoints(self):
"""Delta relationship where both endpoints are hallucinated."""
merged_entities = pd.DataFrame([
_finalized_entity_row("A", entity_id="e1"),
_finalized_entity_row("B", entity_id="e2"),
])
old_rels = pd.DataFrame([
_finalized_relationship_row(
"A", "B", relationship_id="r0", human_readable_id=0
),
])
delta_rels = pd.DataFrame([
_finalized_relationship_row("GHOST_1", "GHOST_2", relationship_id="r1"),
])
merged_rels = _update_and_merge_relationships(old_rels, delta_rels)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 1
assert filtered.iloc[0]["source"] == "A"
assert filtered.iloc[0]["target"] == "B"
def test_all_valid_after_update(self):
"""When all endpoints exist, nothing is filtered."""
merged_entities = pd.DataFrame([
_finalized_entity_row("A", entity_id="e1"),
_finalized_entity_row("B", entity_id="e2"),
_finalized_entity_row("C", entity_id="e3"),
])
old_rels = pd.DataFrame([
_finalized_relationship_row("A", "B", relationship_id="r1"),
])
delta_rels = pd.DataFrame([
_finalized_relationship_row("B", "C", relationship_id="r2"),
])
merged_rels = _update_and_merge_relationships(old_rels, delta_rels)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
assert len(filtered) == 2
def test_old_relationship_becomes_orphan_after_entity_merge(self):
"""Edge case: entity removed in delta makes old relationship orphan.
This can happen if entity resolution during merge drops an
entity that was previously referenced by a relationship.
"""
merged_entities = pd.DataFrame([
_finalized_entity_row("A", entity_id="e1"),
_finalized_entity_row("B", entity_id="e2"),
])
old_rels = pd.DataFrame([
_finalized_relationship_row(
"A", "REMOVED", relationship_id="r1", human_readable_id=0
),
_finalized_relationship_row(
"A", "B", relationship_id="r2", human_readable_id=1
),
])
delta_rels = pd.DataFrame([
_finalized_relationship_row(
"B", "A", relationship_id="r3", human_readable_id=0
),
])
merged_rels = _update_and_merge_relationships(old_rels, delta_rels)
filtered = filter_orphan_relationships(merged_rels, merged_entities)
surviving_pairs = set(zip(filtered["source"], filtered["target"], strict=True))
assert ("A", "REMOVED") not in surviving_pairs
assert len(filtered) >= 1
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/update/test_update_relationships.py",
"license": "MIT License",
"lines": 193,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/indexing/test_finalize_graph.py | # Copyright (C) 2026 Microsoft
# Licensed under the MIT License
"""Tests for the finalize_graph streaming functions.
Covers _build_degree_map, finalize_entities, finalize_relationships,
and the orchestrating finalize_graph function.
"""
from typing import Any
import pytest
from graphrag.data_model.schemas import (
ENTITIES_FINAL_COLUMNS,
RELATIONSHIPS_FINAL_COLUMNS,
)
from graphrag.index.operations.finalize_entities import finalize_entities
from graphrag.index.operations.finalize_relationships import (
finalize_relationships,
)
from graphrag.index.workflows.finalize_graph import (
_build_degree_map,
finalize_graph,
)
from graphrag_storage.tables.table import Table
class FakeTable(Table):
"""In-memory table that supports async iteration and write collection.
Rows passed to write() are collected in ``written`` for assertions.
Each call to ``__aiter__`` resets the read cursor so the table can
be iterated multiple times, matching the real CSVTable behavior
under truncate mode.
"""
def __init__(self, rows: list[dict[str, Any]] | None = None) -> None:
self._rows = list(rows or [])
self._index = 0
self.written: list[dict[str, Any]] = []
def __aiter__(self):
"""Return an async iterator over the seed rows."""
self._index = 0
return self
async def __anext__(self) -> dict[str, Any]:
"""Yield the next row or stop."""
if self._index >= len(self._rows):
raise StopAsyncIteration
row = dict(self._rows[self._index])
self._index += 1
return row
async def length(self) -> int:
"""Return number of seed rows."""
return len(self._rows)
async def has(self, row_id: str) -> bool:
"""Check if a row with the given ID exists in seed rows."""
return any(r.get("id") == row_id for r in self._rows)
async def write(self, row: dict[str, Any]) -> None:
"""Collect written rows for test assertions."""
self.written.append(row)
async def close(self) -> None:
"""No-op."""
def _make_entity_row(
title: str,
entity_type: str = "ENTITY",
description: str = "",
frequency: int = 1,
) -> dict[str, Any]:
"""Build a minimal entity row matching pre-finalization shape."""
return {
"title": title,
"type": entity_type,
"description": description,
"frequency": frequency,
"text_unit_ids": ["tu1"],
}
def _make_relationship_row(
source: str,
target: str,
weight: float = 1.0,
description: str = "",
) -> dict[str, Any]:
"""Build a minimal relationship row matching pre-finalization shape."""
return {
"source": source,
"target": target,
"weight": weight,
"description": description,
"text_unit_ids": ["tu1"],
}
class TestBuildDegreeMap:
"""Tests for the streaming _build_degree_map helper."""
async def test_simple_triangle(self):
"""Three nodes forming a triangle should each have degree 2."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("B", "C"),
_make_relationship_row("A", "C"),
])
result = await _build_degree_map(table)
assert result == {"A": 2, "B": 2, "C": 2}
async def test_star_topology(self):
"""Hub connected to four leaves should have degree 4; leaves degree 1."""
table = FakeTable([
_make_relationship_row("hub", "a"),
_make_relationship_row("hub", "b"),
_make_relationship_row("hub", "c"),
_make_relationship_row("hub", "d"),
])
result = await _build_degree_map(table)
assert result["hub"] == 4
for leaf in ("a", "b", "c", "d"):
assert result[leaf] == 1
async def test_duplicate_edges_deduplicated(self):
"""Duplicate (A, B) edges should be counted only once."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("A", "B"),
])
result = await _build_degree_map(table)
assert result == {"A": 1, "B": 1}
async def test_reversed_duplicate_edges_deduplicated(self):
"""(A, B) and (B, A) are the same undirected edge."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("B", "A"),
])
result = await _build_degree_map(table)
assert result == {"A": 1, "B": 1}
async def test_empty_table(self):
"""Empty relationship table should produce empty degree map."""
table = FakeTable([])
result = await _build_degree_map(table)
assert result == {}
async def test_single_edge(self):
"""One edge yields degree 1 for both endpoints."""
table = FakeTable([_make_relationship_row("X", "Y")])
result = await _build_degree_map(table)
assert result == {"X": 1, "Y": 1}
async def test_disconnected_components(self):
"""Two separate components computed correctly."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("C", "D"),
])
result = await _build_degree_map(table)
assert result == {"A": 1, "B": 1, "C": 1, "D": 1}
class TestFinalizeEntities:
"""Tests for stream-finalize entity rows."""
async def test_enriches_with_degree(self):
"""Entities should receive degree from the degree map."""
table = FakeTable([
_make_entity_row("A"),
_make_entity_row("B"),
])
degree_map = {"A": 3, "B": 1}
await finalize_entities(table, degree_map)
assert len(table.written) == 2
assert table.written[0]["degree"] == 3
assert table.written[1]["degree"] == 1
async def test_missing_degree_defaults_to_zero(self):
"""Entity not in degree map should get degree 0."""
table = FakeTable([_make_entity_row("UNKNOWN")])
degree_map = {"A": 5}
await finalize_entities(table, degree_map)
assert len(table.written) == 1
assert table.written[0]["degree"] == 0
async def test_deduplicates_by_title(self):
"""Duplicate titles should be skipped."""
table = FakeTable([
_make_entity_row("A"),
_make_entity_row("A"),
_make_entity_row("B"),
])
degree_map = {"A": 1, "B": 2}
await finalize_entities(table, degree_map)
assert len(table.written) == 2
titles = [r["title"] for r in table.written]
assert titles == ["A", "B"]
async def test_skips_empty_title(self):
"""Rows with empty or missing title should be skipped."""
table = FakeTable([
_make_entity_row(""),
_make_entity_row("A"),
])
degree_map = {"A": 1}
await finalize_entities(table, degree_map)
assert len(table.written) == 1
assert table.written[0]["title"] == "A"
async def test_assigns_sequential_human_readable_ids(self):
"""human_readable_id should be 0-based sequential."""
table = FakeTable([
_make_entity_row("A"),
_make_entity_row("B"),
_make_entity_row("C"),
])
degree_map = {"A": 1, "B": 1, "C": 1}
await finalize_entities(table, degree_map)
ids = [r["human_readable_id"] for r in table.written]
assert ids == [0, 1, 2]
async def test_assigns_unique_ids(self):
"""Each entity should get a unique UUID id."""
table = FakeTable([
_make_entity_row("A"),
_make_entity_row("B"),
])
degree_map = {"A": 1, "B": 1}
await finalize_entities(table, degree_map)
row_ids = [r["id"] for r in table.written]
assert len(set(row_ids)) == 2
async def test_output_columns_match_schema(self):
"""Written rows should contain exactly the ENTITIES_FINAL_COLUMNS."""
table = FakeTable([_make_entity_row("A")])
degree_map = {"A": 1}
await finalize_entities(table, degree_map)
assert set(table.written[0].keys()) == set(ENTITIES_FINAL_COLUMNS)
async def test_returns_sample_rows_up_to_five(self):
"""Should return at most 5 sample rows."""
rows = [_make_entity_row(f"E{i}") for i in range(8)]
table = FakeTable(rows)
degree_map = {f"E{i}": 1 for i in range(8)}
samples = await finalize_entities(table, degree_map)
assert len(samples) == 5
assert len(table.written) == 8
async def test_empty_table(self):
"""Empty input should produce no output."""
table = FakeTable([])
degree_map = {}
samples = await finalize_entities(table, degree_map)
assert samples == []
assert table.written == []
class TestFinalizeRelationships:
"""Tests for stream-finalize relationship rows."""
async def test_enriches_with_combined_degree(self):
"""combined_degree should be sum of source and target degrees."""
table = FakeTable([_make_relationship_row("A", "B")])
degree_map = {"A": 3, "B": 2}
await finalize_relationships(table, degree_map)
assert len(table.written) == 1
assert table.written[0]["combined_degree"] == 5
async def test_missing_degree_defaults_to_zero(self):
"""Nodes not in degree map contribute 0 to combined_degree."""
table = FakeTable([_make_relationship_row("X", "Y")])
degree_map = {"X": 4}
await finalize_relationships(table, degree_map)
assert table.written[0]["combined_degree"] == 4
async def test_deduplicates_by_source_target(self):
"""Duplicate (source, target) pairs should be skipped."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("A", "B"),
_make_relationship_row("B", "C"),
])
degree_map = {"A": 1, "B": 2, "C": 1}
await finalize_relationships(table, degree_map)
assert len(table.written) == 2
pairs = [(r["source"], r["target"]) for r in table.written]
assert pairs == [("A", "B"), ("B", "C")]
async def test_reversed_pair_not_deduplicated(self):
"""(A,B) and (B,A) are treated as distinct directed edges."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("B", "A"),
])
degree_map = {"A": 1, "B": 1}
await finalize_relationships(table, degree_map)
assert len(table.written) == 2
async def test_assigns_sequential_human_readable_ids(self):
"""human_readable_id should be 0-based sequential."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("B", "C"),
])
degree_map = {"A": 1, "B": 2, "C": 1}
await finalize_relationships(table, degree_map)
ids = [r["human_readable_id"] for r in table.written]
assert ids == [0, 1]
async def test_assigns_unique_ids(self):
"""Each relationship should get a unique UUID id."""
table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("B", "C"),
])
degree_map = {"A": 1, "B": 2, "C": 1}
await finalize_relationships(table, degree_map)
row_ids = [r["id"] for r in table.written]
assert len(set(row_ids)) == 2
async def test_output_columns_match_schema(self):
"""Written rows should contain exactly RELATIONSHIPS_FINAL_COLUMNS."""
table = FakeTable([_make_relationship_row("A", "B")])
degree_map = {"A": 1, "B": 1}
await finalize_relationships(table, degree_map)
assert set(table.written[0].keys()) == set(RELATIONSHIPS_FINAL_COLUMNS)
async def test_returns_sample_rows_up_to_five(self):
"""Should return at most 5 sample rows."""
rows = [_make_relationship_row(f"S{i}", f"T{i}") for i in range(8)]
table = FakeTable(rows)
degree_map = {f"S{i}": 1 for i in range(8)} | {f"T{i}": 1 for i in range(8)}
samples = await finalize_relationships(table, degree_map)
assert len(samples) == 5
assert len(table.written) == 8
async def test_empty_table(self):
"""Empty input should produce no output."""
table = FakeTable([])
degree_map = {}
samples = await finalize_relationships(table, degree_map)
assert samples == []
assert table.written == []
class TestFinalizeGraph:
"""Tests for the orchestrating finalize_graph function."""
async def test_produces_entities_and_relationships_keys(self):
"""Result dict should have 'entities' and 'relationships' keys."""
entities_table = FakeTable([_make_entity_row("A")])
relationships_table = FakeTable([_make_relationship_row("A", "B")])
result = await finalize_graph(entities_table, relationships_table)
assert "entities" in result
assert "relationships" in result
async def test_degree_flows_through_to_entities(self):
"""Entity degree should reflect computed edge degrees."""
entities_table = FakeTable([
_make_entity_row("A"),
_make_entity_row("B"),
_make_entity_row("C"),
])
relationships_table = FakeTable([
_make_relationship_row("A", "B"),
_make_relationship_row("A", "C"),
])
await finalize_graph(entities_table, relationships_table)
degree_by_title = {r["title"]: r["degree"] for r in entities_table.written}
assert degree_by_title["A"] == 2
assert degree_by_title["B"] == 1
assert degree_by_title["C"] == 1
async def test_combined_degree_flows_through_to_relationships(self):
"""Relationship combined_degree should be sum of endpoint degrees."""
entities_table = FakeTable([
_make_entity_row("A"),
_make_entity_row("B"),
])
relationships_table = FakeTable([
_make_relationship_row("A", "B"),
])
await finalize_graph(entities_table, relationships_table)
assert len(relationships_table.written) == 1
assert relationships_table.written[0]["combined_degree"] == 2
async def test_empty_graph(self):
"""Empty tables should produce empty results."""
entities_table = FakeTable([])
relationships_table = FakeTable([])
result = await finalize_graph(entities_table, relationships_table)
assert result == {"entities": [], "relationships": []}
@pytest.mark.parametrize(
("entity_count", "relationship_count"),
[
(3, 2),
(10, 15),
],
ids=["small", "medium"],
)
async def test_all_rows_written(self, entity_count: int, relationship_count: int):
"""All unique entities and relationships should be written."""
entity_rows = [_make_entity_row(f"E{i}") for i in range(entity_count)]
relationship_rows = [
_make_relationship_row(f"E{i}", f"E{(i + 1) % entity_count}")
for i in range(relationship_count)
]
entities_table = FakeTable(entity_rows)
relationships_table = FakeTable(relationship_rows)
await finalize_graph(entities_table, relationships_table)
assert len(entities_table.written) == entity_count
unique_rel_pairs = {(r["source"], r["target"]) for r in relationship_rows}
assert len(relationships_table.written) == len(unique_rel_pairs)
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/test_finalize_graph.py",
"license": "MIT License",
"lines": 364,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag-vectors/graphrag_vectors/filtering.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Generic filter expressions for vector store queries.
This module provides Pydantic-based filter expressions that can be:
1. Built programmatically using the F builder (for humans)
2. Generated as JSON by an LLM (structured output)
3. Serialized/deserialized for storage or transmission
4. Compiled to native query languages by each vector store implementation
Example (human usage):
from graphrag_vectors.filtering import F
# Simple conditions
results = store.similarity_search_by_vector(embedding, k=10, filters=F.status == "active")
results = store.similarity_search_by_vector(embedding, k=10, filters=F.age >= 18)
# Complex conditions
results = store.similarity_search_by_vector(
embedding, k=10,
filters=(F.status == "active") & ((F.role == "admin") | (F.role == "moderator"))
)
Example (LLM structured output / JSON):
{
"and_": [
{"field": "status", "operator": "eq", "value": "active"},
{"field": "age", "operator": "gte", "value": 18}
]
}
"""
from __future__ import annotations
from enum import StrEnum
from typing import Annotated, Any
from pydantic import BaseModel, ConfigDict, Field
class Operator(StrEnum):
"""Comparison operators for filter conditions."""
eq = "eq"
ne = "ne"
gt = "gt"
gte = "gte"
lt = "lt"
lte = "lte"
contains = "contains"
startswith = "startswith"
endswith = "endswith"
in_ = "in"
not_in = "not_in"
exists = "exists"
class Condition(BaseModel):
"""A single filter condition comparing a field to a value.
Attributes
----------
field : str
Name of the metadata field to compare.
operator : Operator
Comparison operator to use.
value : Any
Value to compare against.
Example
-------
Condition(field="status", operator="eq", value="active")
Condition(field="age", operator="gte", value=18)
"""
field: str
operator: Operator
value: Any
def evaluate(self, obj: Any) -> bool:
"""Evaluate this condition against an object.
Parameters
----------
obj : Any
Object with attributes or a dict to evaluate against.
Returns
-------
bool
True if the condition matches.
"""
actual = self._get_field_value(obj)
if self.operator == Operator.exists:
exists = actual is not None
return exists if self.value else not exists
if actual is None:
return False
return self._compare(actual, self.operator, self.value)
def _get_field_value(self, obj: Any) -> Any:
"""Get the field value from an object or dict."""
if isinstance(obj, dict):
return obj.get(self.field)
if hasattr(obj, self.field):
return getattr(obj, self.field)
if hasattr(obj, "data") and isinstance(obj.data, dict):
return obj.data.get(self.field)
return None
def _compare(self, actual: Any, op: Operator, expected: Any) -> bool:
"""Compare actual value against expected using operator."""
match op:
case Operator.eq:
return actual == expected
case Operator.ne:
return actual != expected
case Operator.gt:
return actual > expected
case Operator.gte:
return actual >= expected
case Operator.lt:
return actual < expected
case Operator.lte:
return actual <= expected
case Operator.contains:
if isinstance(actual, str):
return expected in actual
try:
return expected in actual
except TypeError:
return False
case Operator.startswith:
return actual.startswith(expected) if isinstance(actual, str) else False
case Operator.endswith:
return actual.endswith(expected) if isinstance(actual, str) else False
case Operator.in_:
return actual in expected if isinstance(expected, list) else False
case Operator.not_in:
return actual not in expected if isinstance(expected, list) else False
case _:
return False
def __and__(self, other: FilterExpr) -> AndExpr:
"""Combine with AND."""
return _make_and(self, other)
def __or__(self, other: FilterExpr) -> OrExpr:
"""Combine with OR."""
return _make_or(self, other)
def __invert__(self) -> NotExpr:
"""Negate this condition."""
return NotExpr(not_=self)
class AndExpr(BaseModel):
"""Logical AND of multiple filter expressions.
All expressions must match for the AND to be true.
Example
-------
AndExpr(and_=[
Condition(field="status", operator="eq", value="active"),
Condition(field="age", operator="gte", value=18)
])
"""
model_config = ConfigDict(populate_by_name=True)
and_: list[FilterExpr] = Field(validation_alias="and", serialization_alias="and")
def evaluate(self, obj: Any) -> bool:
"""Evaluate AND expression - all must match."""
return all(expr.evaluate(obj) for expr in self.and_)
def __and__(self, other: FilterExpr) -> AndExpr:
"""Combine with AND."""
return _make_and(self, other)
def __or__(self, other: FilterExpr) -> OrExpr:
"""Combine with OR."""
return _make_or(self, other)
def __invert__(self) -> NotExpr:
"""Negate this expression."""
return NotExpr(not_=self)
class OrExpr(BaseModel):
"""Logical OR of multiple filter expressions.
At least one expression must match for the OR to be true.
Example
-------
OrExpr(or_=[
Condition(field="role", operator="eq", value="admin"),
Condition(field="role", operator="eq", value="moderator")
])
"""
model_config = ConfigDict(populate_by_name=True)
or_: list[FilterExpr] = Field(validation_alias="or", serialization_alias="or")
def evaluate(self, obj: Any) -> bool:
"""Evaluate OR expression - at least one must match."""
return any(expr.evaluate(obj) for expr in self.or_)
def __and__(self, other: FilterExpr) -> AndExpr:
"""Combine with AND."""
return _make_and(self, other)
def __or__(self, other: FilterExpr) -> OrExpr:
"""Combine with OR."""
return _make_or(self, other)
def __invert__(self) -> NotExpr:
"""Negate this expression."""
return NotExpr(not_=self)
class NotExpr(BaseModel):
"""Logical NOT of a filter expression.
Inverts the result of the inner expression.
Example
-------
NotExpr(not_=Condition(field="deleted", operator="eq", value=True))
"""
model_config = ConfigDict(populate_by_name=True)
not_: FilterExpr = Field(validation_alias="not", serialization_alias="not")
def evaluate(self, obj: Any) -> bool:
"""Evaluate NOT expression - invert the inner expression."""
return not self.not_.evaluate(obj)
def __and__(self, other: FilterExpr) -> AndExpr:
"""Combine with AND."""
return _make_and(self, other)
def __or__(self, other: FilterExpr) -> OrExpr:
"""Combine with OR."""
return _make_or(self, other)
def __invert__(self) -> FilterExpr:
"""Double negation returns the inner expression."""
return self.not_
# Union type for all filter expressions
FilterExpr = Annotated[
Condition | AndExpr | OrExpr | NotExpr,
Field(discriminator=None),
]
# Update forward references
AndExpr.model_rebuild()
OrExpr.model_rebuild()
NotExpr.model_rebuild()
# ---------------------------------------------------------------------------
# Fluent F builder
# ---------------------------------------------------------------------------
class FieldRef:
"""Reference to a field for building filter expressions with a fluent API.
Example
-------
F.age >= 18 # Condition(field="age", operator="gte", value=18)
F.name == "x" # Condition(field="name", operator="eq", value="x")
"""
def __init__(self, name: str) -> None:
self.name = name
def __eq__(self, other: object) -> Condition: # type: ignore[override]
"""Create an equality condition."""
return Condition(field=self.name, operator=Operator.eq, value=other)
def __ne__(self, other: object) -> Condition: # type: ignore[override]
"""Create a not-equal condition."""
return Condition(field=self.name, operator=Operator.ne, value=other)
def __gt__(self, other: Any) -> Condition:
"""Create a greater-than condition."""
return Condition(field=self.name, operator=Operator.gt, value=other)
def __ge__(self, other: Any) -> Condition:
"""Create a greater-than-or-equal condition."""
return Condition(field=self.name, operator=Operator.gte, value=other)
def __lt__(self, other: Any) -> Condition:
"""Create a less-than condition."""
return Condition(field=self.name, operator=Operator.lt, value=other)
def __le__(self, other: Any) -> Condition:
"""Create a less-than-or-equal condition."""
return Condition(field=self.name, operator=Operator.lte, value=other)
def contains(self, value: str) -> Condition:
"""Create a 'contains' condition."""
return Condition(field=self.name, operator=Operator.contains, value=value)
def startswith(self, value: str) -> Condition:
"""Create a 'startswith' condition."""
return Condition(field=self.name, operator=Operator.startswith, value=value)
def endswith(self, value: str) -> Condition:
"""Create a 'endswith' condition."""
return Condition(field=self.name, operator=Operator.endswith, value=value)
def in_(self, values: list[Any]) -> Condition:
"""Create an 'in' condition."""
return Condition(field=self.name, operator=Operator.in_, value=values)
def not_in(self, values: list[Any]) -> Condition:
"""Create a 'not_in' condition."""
return Condition(field=self.name, operator=Operator.not_in, value=values)
def exists(self, value: bool = True) -> Condition:
"""Create an 'exists' condition."""
return Condition(field=self.name, operator=Operator.exists, value=value)
class _FieldBuilder:
"""Builder for creating field references via attribute access.
Example
-------
F.status == "active" # Returns Condition
F.age >= 18 # Returns Condition
"""
def __getattr__(self, name: str) -> FieldRef:
"""Create a FieldRef for the given field name."""
return FieldRef(name)
# Singleton for convenient import
F = _FieldBuilder()
# ---------------------------------------------------------------------------
# Operator overloads for combining expressions with & | ~
# ---------------------------------------------------------------------------
def _make_and(left: FilterExpr, right: FilterExpr) -> AndExpr:
"""Create AND expression, flattening nested ANDs."""
expressions: list[FilterExpr] = []
if isinstance(left, AndExpr):
expressions.extend(left.and_)
else:
expressions.append(left)
if isinstance(right, AndExpr):
expressions.extend(right.and_)
else:
expressions.append(right)
return AndExpr(and_=expressions)
def _make_or(left: FilterExpr, right: FilterExpr) -> OrExpr:
"""Create OR expression, flattening nested ORs."""
expressions: list[FilterExpr] = []
if isinstance(left, OrExpr):
expressions.extend(left.or_)
else:
expressions.append(left)
if isinstance(right, OrExpr):
expressions.extend(right.or_)
else:
expressions.append(right)
return OrExpr(or_=expressions)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-vectors/graphrag_vectors/filtering.py",
"license": "MIT License",
"lines": 295,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-vectors/graphrag_vectors/timestamp.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Timestamp explosion for vector store indexing.
Converts an ISO 8601 timestamp string into a set of filterable component
fields, enabling temporal queries like "find documents from a Monday" or
"find documents from Q3 2024" using the standard filter expression system.
Built-in timestamps:
- create_date: when the document was first created
- update_date: when the document was last updated
User-defined date fields can also be exploded by declaring them with
type "date" in the fields config.
"""
from datetime import datetime
# Suffixes for the exploded component fields
_SUFFIXES: dict[str, str] = {
"year": "int",
"month": "int",
"month_name": "str",
"day": "int",
"day_of_week": "str",
"hour": "int",
"quarter": "int",
}
def _timestamp_fields_for(prefix: str) -> dict[str, str]:
"""Return the exploded field definitions for a given prefix."""
return {f"{prefix}_{suffix}": ftype for suffix, ftype in _SUFFIXES.items()}
# Combined field definitions for both timestamps
TIMESTAMP_FIELDS: dict[str, str] = {
**_timestamp_fields_for("create_date"),
**_timestamp_fields_for("update_date"),
}
def explode_timestamp(
iso_timestamp: str | None, prefix: str = "create_date"
) -> dict[str, str | int]:
"""Explode an ISO 8601 timestamp into filterable component fields.
Parameters
----------
iso_timestamp : str
An ISO 8601 formatted datetime string (e.g. "2024-03-15T14:30:00").
prefix : str
Field name prefix, typically "create_date" or "update_date".
Returns
-------
dict[str, str | int]
Dictionary with timestamp component fields, e.g.:
- {prefix}_year (int): e.g. 2024
- {prefix}_month (int): 1-12
- {prefix}_month_name (str): e.g. "March"
- {prefix}_day (int): 1-31
- {prefix}_day_of_week (str): e.g. "Monday"
- {prefix}_hour (int): 0-23
- {prefix}_quarter (int): 1-4
Example
-------
>>> explode_timestamp(
... "2024-03-15T14:30:00",
... "create_date",
... )
{
'create_date_year': 2024,
'create_date_month': 3,
'create_date_month_name': 'March',
'create_date_day': 15,
'create_date_day_of_week': 'Friday',
'create_date_hour': 14,
'create_date_quarter': 1,
}
"""
if not iso_timestamp:
return {}
dt = datetime.fromisoformat(iso_timestamp)
return {
f"{prefix}_year": dt.year,
f"{prefix}_month": dt.month,
f"{prefix}_month_name": dt.strftime("%B"),
f"{prefix}_day": dt.day,
f"{prefix}_day_of_week": dt.strftime("%A"),
f"{prefix}_hour": dt.hour,
f"{prefix}_quarter": (dt.month - 1) // 3 + 1,
}
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-vectors/graphrag_vectors/timestamp.py",
"license": "MIT License",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/vector_stores/test_filtering.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Unit tests for the filtering module (no backend required)."""
import json
from graphrag_vectors.filtering import (
AndExpr,
Condition,
F,
FilterExpr,
NotExpr,
Operator,
OrExpr,
)
# ── Condition.evaluate ──────────────────────────────────────────────────────
class TestConditionEvaluate:
"""Tests for Condition.evaluate() client-side evaluation."""
def test_eq(self):
cond = Condition(field="color", operator=Operator.eq, value="red")
assert cond.evaluate({"color": "red"}) is True
assert cond.evaluate({"color": "blue"}) is False
def test_ne(self):
cond = Condition(field="color", operator=Operator.ne, value="red")
assert cond.evaluate({"color": "blue"}) is True
assert cond.evaluate({"color": "red"}) is False
def test_gt(self):
cond = Condition(field="score", operator=Operator.gt, value=5)
assert cond.evaluate({"score": 10}) is True
assert cond.evaluate({"score": 5}) is False
assert cond.evaluate({"score": 3}) is False
def test_gte(self):
cond = Condition(field="score", operator=Operator.gte, value=5)
assert cond.evaluate({"score": 5}) is True
assert cond.evaluate({"score": 4}) is False
def test_lt(self):
cond = Condition(field="score", operator=Operator.lt, value=5)
assert cond.evaluate({"score": 3}) is True
assert cond.evaluate({"score": 5}) is False
def test_lte(self):
cond = Condition(field="score", operator=Operator.lte, value=5)
assert cond.evaluate({"score": 5}) is True
assert cond.evaluate({"score": 6}) is False
def test_in(self):
cond = Condition(field="tag", operator=Operator.in_, value=["a", "b", "c"])
assert cond.evaluate({"tag": "b"}) is True
assert cond.evaluate({"tag": "z"}) is False
def test_missing_field_returns_false(self):
cond = Condition(field="missing", operator=Operator.eq, value=42)
assert cond.evaluate({"other": 1}) is False
# ── AndExpr.evaluate ────────────────────────────────────────────────────────
class TestAndEvaluate:
"""Tests for AndExpr.evaluate() client-side evaluation."""
def test_all_true(self):
expr = AndExpr(
and_=[
Condition(field="a", operator=Operator.eq, value=1),
Condition(field="b", operator=Operator.eq, value=2),
]
)
assert expr.evaluate({"a": 1, "b": 2}) is True
def test_one_false(self):
expr = AndExpr(
and_=[
Condition(field="a", operator=Operator.eq, value=1),
Condition(field="b", operator=Operator.eq, value=2),
]
)
assert expr.evaluate({"a": 1, "b": 99}) is False
# ── OrExpr.evaluate ─────────────────────────────────────────────────────────
class TestOrEvaluate:
"""Tests for OrExpr.evaluate() client-side evaluation."""
def test_one_true(self):
expr = OrExpr(
or_=[
Condition(field="a", operator=Operator.eq, value=1),
Condition(field="b", operator=Operator.eq, value=2),
]
)
assert expr.evaluate({"a": 1, "b": 99}) is True
def test_none_true(self):
expr = OrExpr(
or_=[
Condition(field="a", operator=Operator.eq, value=1),
Condition(field="b", operator=Operator.eq, value=2),
]
)
assert expr.evaluate({"a": 0, "b": 0}) is False
# ── NotExpr.evaluate ────────────────────────────────────────────────────────
class TestNotEvaluate:
"""Tests for NotExpr.evaluate() client-side evaluation."""
def test_negates_true(self):
inner = Condition(field="a", operator=Operator.eq, value=1)
assert NotExpr(not_=inner).evaluate({"a": 1}) is False
def test_negates_false(self):
inner = Condition(field="a", operator=Operator.eq, value=1)
assert NotExpr(not_=inner).evaluate({"a": 2}) is True
# ── F builder ───────────────────────────────────────────────────────────────
class TestFBuilder:
"""Tests for the F fluent builder."""
def test_eq_produces_condition(self):
expr = F.color == "red"
assert isinstance(expr, Condition)
assert expr.field == "color"
assert expr.operator == Operator.eq
assert expr.value == "red"
def test_ne(self):
expr = F.color != "red"
assert isinstance(expr, Condition)
assert expr.operator == Operator.ne
def test_gt(self):
expr = F.score > 5
assert isinstance(expr, Condition)
assert expr.operator == Operator.gt
assert expr.value == 5
def test_gte(self):
expr = F.score >= 5
assert isinstance(expr, Condition)
assert expr.operator == Operator.gte
def test_lt(self):
expr = F.score < 5
assert isinstance(expr, Condition)
assert expr.operator == Operator.lt
def test_lte(self):
expr = F.score <= 5
assert isinstance(expr, Condition)
assert expr.operator == Operator.lte
def test_in(self):
expr = F.tag.in_(["a", "b"])
assert isinstance(expr, Condition)
assert expr.operator == Operator.in_
assert expr.value == ["a", "b"]
# ── Operator overloads ──────────────────────────────────────────────────────
class TestOperatorOverloads:
"""Tests for & | ~ operator overloads on expression types."""
def test_and_two_conditions(self):
expr = (F.a == 1) & (F.b == 2)
assert isinstance(expr, AndExpr)
assert len(expr.and_) == 2
def test_or_two_conditions(self):
expr = (F.a == 1) | (F.b == 2)
assert isinstance(expr, OrExpr)
assert len(expr.or_) == 2
def test_not_condition(self):
expr = ~(F.a == 1)
assert isinstance(expr, NotExpr)
assert isinstance(expr.not_, Condition)
def test_not_and(self):
expr = ~((F.a == 1) & (F.b == 2))
assert isinstance(expr, NotExpr)
assert isinstance(expr.not_, AndExpr)
def test_and_or_nesting(self):
"""Test complex nesting: (a & b) | c."""
expr = ((F.a == 1) & (F.b == 2)) | (F.c == 3)
assert isinstance(expr, OrExpr)
# ── AND/OR flattening ──────────────────────────────────────────────────────
class TestFlattening:
"""Tests for AND/OR expression flattening (associativity)."""
def test_and_flattening(self):
"""(a & b) & c should produce a flat AndExpr with 3 conditions."""
expr = (F.a == 1) & (F.b == 2) & (F.c == 3)
assert isinstance(expr, AndExpr)
assert len(expr.and_) == 3
def test_or_flattening(self):
"""(a | b) | c should produce a flat OrExpr with 3 conditions."""
expr = (F.a == 1) | (F.b == 2) | (F.c == 3)
assert isinstance(expr, OrExpr)
assert len(expr.or_) == 3
# ── Double negation ────────────────────────────────────────────────────────
class TestDoubleNegation:
"""Tests for double negation behavior."""
def test_double_negation(self):
"""~~expr should return the inner expression directly."""
inner = F.a == 1
double_neg = ~(~inner)
# Double negation via __invert__ on NotExpr returns self.not_
assert isinstance(double_neg, Condition)
assert double_neg.evaluate({"a": 1}) is True
assert double_neg.evaluate({"a": 2}) is False
# ── JSON round-trip ─────────────────────────────────────────────────────────
class TestJsonRoundtrip:
"""Tests for JSON serialization/deserialization round-trips."""
def _roundtrip(self, expr: FilterExpr) -> FilterExpr:
"""Serialize and deserialize a filter expression."""
payload = expr.model_dump()
json_str = json.dumps(payload)
parsed = json.loads(json_str)
# Determine which type to deserialize based on the model's discriminator
if isinstance(expr, Condition):
return Condition.model_validate(parsed)
if isinstance(expr, AndExpr):
return AndExpr.model_validate(parsed)
if isinstance(expr, OrExpr):
return OrExpr.model_validate(parsed)
if isinstance(expr, NotExpr):
return NotExpr.model_validate(parsed)
msg = f"Unknown type: {type(expr)}"
raise TypeError(msg)
def test_condition_roundtrip(self):
original = Condition(field="x", operator=Operator.eq, value=42)
restored = self._roundtrip(original)
assert isinstance(restored, Condition)
assert restored.field == "x"
assert restored.operator == Operator.eq
assert restored.value == 42
def test_and_roundtrip(self):
original = AndExpr(
and_=[
Condition(field="a", operator=Operator.gt, value=1),
Condition(field="b", operator=Operator.lt, value=10),
]
)
restored = self._roundtrip(original)
assert isinstance(restored, AndExpr)
assert len(restored.and_) == 2
def test_or_roundtrip(self):
original = OrExpr(
or_=[
Condition(field="a", operator=Operator.eq, value="x"),
Condition(field="b", operator=Operator.eq, value="y"),
]
)
restored = self._roundtrip(original)
assert isinstance(restored, OrExpr)
assert len(restored.or_) == 2
def test_not_roundtrip(self):
original = NotExpr(
not_=Condition(field="z", operator=Operator.in_, value=[1, 2, 3])
)
restored = self._roundtrip(original)
assert isinstance(restored, NotExpr)
assert isinstance(restored.not_, Condition)
def test_complex_nested_roundtrip(self):
"""Test a deeply nested expression survives round-trip."""
original = AndExpr(
and_=[
OrExpr(
or_=[
Condition(field="a", operator=Operator.eq, value=1),
Condition(field="b", operator=Operator.eq, value=2),
]
),
NotExpr(not_=Condition(field="c", operator=Operator.gt, value=10)),
]
)
restored = self._roundtrip(original)
assert isinstance(restored, AndExpr)
assert len(restored.and_) == 2
# Verify the evaluate logic still works after round-trip
assert restored.evaluate({"a": 1, "b": 99, "c": 5}) is True
assert restored.evaluate({"a": 1, "b": 99, "c": 15}) is False
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/vector_stores/test_filtering.py",
"license": "MIT License",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/vector_stores/test_timestamp.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Unit tests for the timestamp module (no backend required)."""
import pytest
from graphrag_vectors.timestamp import (
TIMESTAMP_FIELDS,
_timestamp_fields_for,
explode_timestamp,
)
class TestExplodeTimestamp:
"""Tests for explode_timestamp()."""
def test_basic_explosion(self):
result = explode_timestamp("2024-03-15T14:30:00", "created")
assert result["created_year"] == 2024
assert result["created_month"] == 3
assert result["created_month_name"] == "March"
assert result["created_day"] == 15
assert result["created_day_of_week"] == "Friday"
assert result["created_hour"] == 14
assert result["created_quarter"] == 1
def test_all_keys_present(self):
result = explode_timestamp("2024-01-01T00:00:00", "ts")
expected_keys = {
"ts_year",
"ts_month",
"ts_month_name",
"ts_day",
"ts_day_of_week",
"ts_hour",
"ts_quarter",
}
assert set(result.keys()) == expected_keys
def test_empty_string_returns_empty(self):
result = explode_timestamp("", "ts")
assert result == {}
def test_none_returns_empty(self):
result = explode_timestamp(None, "ts")
assert result == {}
class TestExplodeTimestampQuarterBoundaries:
"""Tests for correct quarter assignment across all months."""
@pytest.mark.parametrize(
("month", "expected_quarter"),
[
("01", 1),
("02", 1),
("03", 1),
("04", 2),
("05", 2),
("06", 2),
("07", 3),
("08", 3),
("09", 3),
("10", 4),
("11", 4),
("12", 4),
],
)
def test_quarter(self, month, expected_quarter):
result = explode_timestamp(f"2024-{month}-15T12:00:00", "d")
assert result["d_quarter"] == expected_quarter
class TestTimestampFieldsForPrefix:
"""Tests for _timestamp_fields_for() helper."""
def test_produces_correct_keys(self):
fields = _timestamp_fields_for("mydate")
expected_keys = {
"mydate_year",
"mydate_month",
"mydate_month_name",
"mydate_day",
"mydate_day_of_week",
"mydate_hour",
"mydate_quarter",
}
assert set(fields.keys()) == expected_keys
def test_types(self):
fields = _timestamp_fields_for("ts")
assert fields["ts_year"] == "int"
assert fields["ts_month"] == "int"
assert fields["ts_month_name"] == "str"
assert fields["ts_day"] == "int"
assert fields["ts_day_of_week"] == "str"
assert fields["ts_hour"] == "int"
assert fields["ts_quarter"] == "int"
class TestTimestampFieldsConstant:
"""Tests for the TIMESTAMP_FIELDS combined constant."""
def test_contains_create_and_update_fields(self):
assert "create_date_year" in TIMESTAMP_FIELDS
assert "update_date_year" in TIMESTAMP_FIELDS
assert "create_date_month_name" in TIMESTAMP_FIELDS
assert "update_date_month_name" in TIMESTAMP_FIELDS
def test_total_count(self):
# 7 fields * 2 prefixes = 14
assert len(TIMESTAMP_FIELDS) == 14
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/vector_stores/test_timestamp.py",
"license": "MIT License",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/indexing/operations/embed_text/test_embed_text.py | # Copyright (C) 2026 Microsoft
# Licensed under the MIT License
"""Unit tests for the streaming embed_text operation."""
from collections.abc import AsyncIterator
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import numpy as np
import pytest
from graphrag.callbacks.noop_workflow_callbacks import (
NoopWorkflowCallbacks,
)
from graphrag.index.operations.embed_text.embed_text import embed_text
from graphrag.index.operations.embed_text.run_embed_text import (
TextEmbeddingResult,
)
from graphrag_storage.tables.table import Table
class FakeInputTable(Table):
"""In-memory table that yields rows via async iteration."""
def __init__(self, rows: list[dict[str, Any]]) -> None:
"""Store the rows to be yielded."""
self._rows = rows
def __aiter__(self) -> AsyncIterator[dict[str, Any]]:
"""Return an async iterator yielding each stored row."""
return self._iter()
async def _iter(self) -> AsyncIterator[dict[str, Any]]:
"""Yield rows one at a time."""
for row in self._rows:
yield dict(row)
async def length(self) -> int:
"""Return the number of rows."""
return len(self._rows)
async def has(self, row_id: str) -> bool:
"""Check if a row with the given ID exists."""
return any(r.get("id") == row_id for r in self._rows)
async def write(self, row: dict[str, Any]) -> None:
"""No-op write (input table is read-only)."""
async def close(self) -> None:
"""No-op close."""
class FakeOutputTable(Table):
"""Collects rows written via write() for assertion."""
def __init__(self) -> None:
"""Initialize empty row collection."""
self.rows: list[dict[str, Any]] = []
def __aiter__(self) -> AsyncIterator[dict[str, Any]]:
"""Yield collected rows."""
return self._iter()
async def _iter(self) -> AsyncIterator[dict[str, Any]]:
"""Yield rows one at a time."""
for row in self.rows:
yield row
async def length(self) -> int:
"""Return the number of written rows."""
return len(self.rows)
async def has(self, row_id: str) -> bool:
"""Check if a row with the given ID was written."""
return any(r.get("id") == row_id for r in self.rows)
async def write(self, row: dict[str, Any]) -> None:
"""Append a row to the collection."""
self.rows.append(row)
async def close(self) -> None:
"""No-op close."""
def _make_mock_vector_store():
"""Create a mock vector store with create_index and load_documents."""
store = MagicMock()
store.create_index = MagicMock()
store.load_documents = MagicMock()
return store
def _make_mock_model(embedding_values: list[float]):
"""Create a mock model that returns fixed embeddings."""
model = MagicMock()
model.tokenizer = MagicMock()
return model, embedding_values
def _make_embedding_result(count: int, values: list[float]) -> TextEmbeddingResult:
"""Build a TextEmbeddingResult with count copies of values."""
return TextEmbeddingResult(embeddings=[list(values) for _ in range(count)])
@pytest.mark.asyncio
async def test_embed_text_basic():
"""Verify basic embedding: rows flow through to vector store and output table."""
rows = [
{"id": "a", "text": "hello world"},
{"id": "b", "text": "foo bar"},
{"id": "c", "text": "baz qux"},
]
input_table = FakeInputTable(rows)
output_table = FakeOutputTable()
vector_store = _make_mock_vector_store()
embedding_values = [1.0, 2.0, 3.0]
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.return_value = _make_embedding_result(3, embedding_values)
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
output_table=output_table,
)
assert count == 3
assert len(output_table.rows) == 3
assert output_table.rows[0]["id"] == "a"
assert output_table.rows[0]["embedding"] == embedding_values
assert output_table.rows[2]["id"] == "c"
vector_store.create_index.assert_called_once()
vector_store.load_documents.assert_called_once()
docs = vector_store.load_documents.call_args[0][0]
assert len(docs) == 3
assert docs[0].id == "a"
assert docs[1].id == "b"
@pytest.mark.asyncio
async def test_embed_text_batching():
"""Verify rows are flushed in batches sized by batch_size * num_threads.
With batch_size=2 and num_threads=4, each flush holds up to
8 rows (enough to produce 4 API batches that saturate the
concurrency limit). 10 rows should produce 2 flushes:
one of 8 rows and a final remainder of 2.
"""
rows = [{"id": str(i), "text": f"text {i}"} for i in range(10)]
input_table = FakeInputTable(rows)
vector_store = _make_mock_vector_store()
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.side_effect = [
_make_embedding_result(8, [1.0]),
_make_embedding_result(2, [2.0]),
]
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=2,
batch_max_tokens=8191,
num_threads=4,
vector_store=vector_store,
)
assert count == 10
assert mock_run.call_count == 2
assert vector_store.load_documents.call_count == 2
@pytest.mark.asyncio
async def test_embed_text_pretransformed_rows():
"""Verify rows pre-transformed by table layer are embedded correctly."""
rows = [
{
"id": "1",
"title": "Alpha",
"description": "First",
"combined": "Alpha:First",
},
{
"id": "2",
"title": "Beta",
"description": "Second",
"combined": "Beta:Second",
},
]
input_table = FakeInputTable(rows)
output_table = FakeOutputTable()
vector_store = _make_mock_vector_store()
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.return_value = _make_embedding_result(2, [0.5])
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="combined",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
output_table=output_table,
)
assert count == 2
texts_arg = mock_run.call_args[0][0]
assert texts_arg == ["Alpha:First", "Beta:Second"]
@pytest.mark.asyncio
async def test_embed_text_none_values_filled():
"""Verify None embed_column values are replaced with empty string."""
rows = [
{"id": "1", "text": None},
{"id": "2", "text": "real text"},
]
input_table = FakeInputTable(rows)
vector_store = _make_mock_vector_store()
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.return_value = _make_embedding_result(2, [1.0])
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
)
assert count == 2
texts_arg = mock_run.call_args[0][0]
assert texts_arg == ["", "real text"]
@pytest.mark.asyncio
async def test_embed_text_no_output_table():
"""Verify embedding works without an output table (no snapshot)."""
rows = [{"id": "x", "text": "data"}]
input_table = FakeInputTable(rows)
vector_store = _make_mock_vector_store()
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.return_value = _make_embedding_result(1, [9.0])
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
output_table=None,
)
assert count == 1
vector_store.load_documents.assert_called_once()
@pytest.mark.asyncio
async def test_embed_text_empty_input():
"""Verify zero rows returns zero count with no calls."""
input_table = FakeInputTable([])
vector_store = _make_mock_vector_store()
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
)
assert count == 0
mock_run.assert_not_called()
vector_store.load_documents.assert_not_called()
@pytest.mark.asyncio
async def test_embed_text_numpy_array_vectors():
"""Verify np.ndarray embeddings are converted to plain lists."""
rows = [
{"id": "a", "text": "hello"},
{"id": "b", "text": "world"},
]
input_table = FakeInputTable(rows)
output_table = FakeOutputTable()
vector_store = _make_mock_vector_store()
numpy_embeddings: list[list[float] | None] = [
np.array([1.0, 2.0]).tolist(),
np.array([3.0, 4.0]).tolist(),
]
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
# Simulate run_embed_text returning np.ndarray objects at runtime
# by replacing the result embeddings after construction.
result = TextEmbeddingResult(embeddings=numpy_embeddings)
result.embeddings = [np.array([1.0, 2.0]), np.array([3.0, 4.0])] # type: ignore[list-item]
mock_run.return_value = result
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
output_table=output_table,
)
assert count == 2
docs = vector_store.load_documents.call_args[0][0]
assert docs[0].vector == [1.0, 2.0]
assert docs[1].vector == [3.0, 4.0]
assert type(docs[0].vector) is list
assert type(docs[1].vector) is list
assert output_table.rows[0]["embedding"] == [1.0, 2.0]
assert type(output_table.rows[0]["embedding"]) is list
@pytest.mark.asyncio
async def test_embed_text_partial_none_embeddings():
"""Verify rows with None embeddings are skipped in store and output."""
rows = [
{"id": "a", "text": "good"},
{"id": "b", "text": "failed"},
{"id": "c", "text": "also good"},
]
input_table = FakeInputTable(rows)
output_table = FakeOutputTable()
vector_store = _make_mock_vector_store()
mixed_embeddings = [[1.0, 2.0], None, [3.0, 4.0]]
with patch(
"graphrag.index.operations.embed_text.embed_text.run_embed_text",
new_callable=AsyncMock,
) as mock_run:
mock_run.return_value = TextEmbeddingResult(embeddings=mixed_embeddings)
count = await embed_text(
input_table=input_table,
callbacks=NoopWorkflowCallbacks(),
model=MagicMock(),
tokenizer=MagicMock(),
embed_column="text",
batch_size=10,
batch_max_tokens=8191,
num_threads=1,
vector_store=vector_store,
output_table=output_table,
)
assert count == 3
docs = vector_store.load_documents.call_args[0][0]
assert len(docs) == 2
assert docs[0].id == "a"
assert docs[1].id == "c"
assert len(output_table.rows) == 2
assert output_table.rows[0]["id"] == "a"
assert output_table.rows[1]["id"] == "c"
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/operations/embed_text/test_embed_text.py",
"license": "MIT License",
"lines": 344,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/verbs/test_update_text_embeddings.py | # Copyright (C) 2026 Microsoft
# Licensed under the MIT License
"""Verb test for the update_text_embeddings workflow."""
from unittest.mock import patch
from graphrag.config.embeddings import all_embeddings
from graphrag.index.workflows.update_text_embeddings import (
run_workflow,
)
from tests.unit.config.utils import get_default_graphrag_config
from .util import create_test_context
async def test_update_text_embeddings():
"""Verify update_text_embeddings produces embedding tables.
Mocks get_update_table_providers to return the test context's
output_table_provider, simulating the merged tables written by
upstream update workflows.
"""
context = await create_test_context(
storage=[
"documents",
"relationships",
"text_units",
"entities",
"community_reports",
]
)
context.state["update_timestamp"] = "20260220-000000"
config = get_default_graphrag_config()
llm_settings = config.get_embedding_model_config(
config.embed_text.embedding_model_id
)
llm_settings.type = "mock"
llm_settings.mock_responses = [1.0] * 3072
config.embed_text.names = list(all_embeddings)
config.snapshots.embeddings = True
with patch(
"graphrag.index.workflows.update_text_embeddings.get_update_table_providers",
) as mock_providers:
mock_providers.return_value = (
context.output_table_provider,
None,
None,
)
await run_workflow(config, context)
parquet_files = context.output_storage.keys()
for field in all_embeddings:
assert f"embeddings.{field}.parquet" in parquet_files
entity_embeddings = await context.output_table_provider.read_dataframe(
"embeddings.entity_description"
)
assert len(entity_embeddings.columns) == 2
assert "id" in entity_embeddings.columns
assert "embedding" in entity_embeddings.columns
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/verbs/test_update_text_embeddings.py",
"license": "MIT License",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag/graphrag/data_model/row_transformers.py | # Copyright (C) 2026 Microsoft
"""Row-level type coercion for streaming Table reads.
Each transformer converts a raw ``dict[str, Any]`` row (as produced by
``csv.DictReader``, where every value is a string) into a dict with
properly typed fields. They serve the same purpose as the DataFrame-
based ``*_typed`` helpers in ``dfs.py``, but operate on single rows so
they can be passed as the *transformer* argument to
``TableProvider.open()``.
"""
from typing import Any
from graphrag.data_model.dfs import split_list_column
def _safe_int(value: Any, fill: int = -1) -> int:
"""Coerce a value to int, returning *fill* when missing or empty.
Handles NaN from Parquet float-promoted nullable int columns
(``row.to_dict()`` yields ``numpy.float64(nan)``) and any other
non-convertible type.
"""
if value is None or value == "":
return fill
try:
return int(value)
except (ValueError, TypeError):
return fill
def _safe_float(value: Any, fill: float = 0.0) -> float:
"""Coerce a value to float, returning *fill* when missing or empty.
Also applies *fill* when the value is NaN (e.g. from Parquet
nullable columns), keeping behavior consistent with the
DataFrame-level ``fillna(fill).astype(float)`` pattern.
"""
if value is None or value == "":
return fill
try:
result = float(value)
except (ValueError, TypeError):
return fill
# math.isnan without importing math
if result != result:
return fill
return result
def _coerce_list(value: Any) -> list[Any]:
"""Parse a value into a list, handling CSV string and array types.
Handles three cases:
- str: CSV-encoded list (e.g. from CSVTable rows)
- list: already a Python list (pass-through)
- array-like with ``tolist`` (e.g. numpy.ndarray from ParquetTable
``row.to_dict()``)
"""
if isinstance(value, str):
return split_list_column(value)
if isinstance(value, list):
return value
if hasattr(value, "tolist"):
return value.tolist()
return []
# -- entities (mirrors entities_typed) ------------------------------------
def transform_entity_row(row: dict[str, Any]) -> dict[str, Any]:
"""Coerce types for an entity row.
Mirrors ``entities_typed``: ``human_readable_id`` -> int,
``text_unit_ids`` -> list, ``frequency`` -> int, ``degree`` -> int.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
if "text_unit_ids" in row:
row["text_unit_ids"] = _coerce_list(row["text_unit_ids"])
if "frequency" in row:
row["frequency"] = _safe_int(row["frequency"], 0)
if "degree" in row:
row["degree"] = _safe_int(row["degree"], 0)
return row
def transform_entity_row_for_embedding(
row: dict[str, Any],
) -> dict[str, Any]:
"""Add a title_description column for embedding generation."""
title = row.get("title") or ""
description = row.get("description") or ""
row["title_description"] = f"{title}:{description}"
return row
# -- relationships (mirrors relationships_typed) --------------------------
def transform_relationship_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a relationship row.
Mirrors ``relationships_typed``: ``human_readable_id`` -> int,
``weight`` -> float, ``combined_degree`` -> int,
``text_unit_ids`` -> list.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
if "weight" in row:
row["weight"] = _safe_float(row["weight"])
if "combined_degree" in row:
row["combined_degree"] = _safe_int(
row["combined_degree"],
0,
)
if "text_unit_ids" in row:
row["text_unit_ids"] = _coerce_list(row["text_unit_ids"])
return row
# -- communities (mirrors communities_typed) ------------------------------
def transform_community_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a community row.
Mirrors ``communities_typed``: ``human_readable_id`` -> int,
``community`` -> int, ``level`` -> int, ``children`` -> list,
``entity_ids`` -> list, ``relationship_ids`` -> list,
``text_unit_ids`` -> list, ``period`` -> str, ``size`` -> int.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
row["community"] = _safe_int(row.get("community"))
row["level"] = _safe_int(row.get("level"))
row["children"] = _coerce_list(row.get("children"))
if "entity_ids" in row:
row["entity_ids"] = _coerce_list(row["entity_ids"])
if "relationship_ids" in row:
row["relationship_ids"] = _coerce_list(
row["relationship_ids"],
)
if "text_unit_ids" in row:
row["text_unit_ids"] = _coerce_list(row["text_unit_ids"])
row["period"] = str(row.get("period", ""))
row["size"] = _safe_int(row.get("size"), 0)
return row
# -- community reports (mirrors community_reports_typed) ------------------
def transform_community_report_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a community report row.
Mirrors ``community_reports_typed``: ``human_readable_id`` -> int,
``community`` -> int, ``level`` -> int, ``children`` -> list,
``rank`` -> float, ``findings`` -> list, ``size`` -> int.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
row["community"] = _safe_int(row.get("community"))
row["level"] = _safe_int(row.get("level"))
row["children"] = _coerce_list(row.get("children"))
row["rank"] = _safe_float(row.get("rank"))
row["findings"] = _coerce_list(row.get("findings"))
row["size"] = _safe_int(row.get("size"), 0)
return row
# -- covariates (mirrors covariates_typed) --------------------------------
def transform_covariate_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a covariate row.
Mirrors ``covariates_typed``: ``human_readable_id`` -> int.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
return row
# -- text units (mirrors text_units_typed) --------------------------------
def transform_text_unit_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a text-unit row.
Mirrors ``text_units_typed``: ``human_readable_id`` -> int,
``n_tokens`` -> int, ``entity_ids`` -> list,
``relationship_ids`` -> list, ``covariate_ids`` -> list.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
row["n_tokens"] = _safe_int(row.get("n_tokens"), 0)
if "entity_ids" in row:
row["entity_ids"] = _coerce_list(row["entity_ids"])
if "relationship_ids" in row:
row["relationship_ids"] = _coerce_list(
row["relationship_ids"],
)
if "covariate_ids" in row:
row["covariate_ids"] = _coerce_list(
row["covariate_ids"],
)
return row
# -- documents (mirrors documents_typed) ----------------------------------
def transform_document_row(
row: dict[str, Any],
) -> dict[str, Any]:
"""Coerce types for a document row.
Mirrors ``documents_typed``: ``human_readable_id`` -> int,
``text_unit_ids`` -> list.
"""
if "human_readable_id" in row:
row["human_readable_id"] = _safe_int(
row["human_readable_id"],
)
if "text_unit_ids" in row:
row["text_unit_ids"] = _coerce_list(row["text_unit_ids"])
return row
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/data_model/row_transformers.py",
"license": "MIT License",
"lines": 202,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/storage/test_csv_table.py | # Copyright (C) 2026 Microsoft
"""Tests for CSVTable temp-file write strategy and streaming behavior.
When truncate=True, CSVTable writes to a temporary file and moves it
over the original on close(). This allows safe concurrent reads from
the original while writes are in progress — the pattern used by
create_final_text_units where the same file is read and written.
"""
import csv
from pathlib import Path
from typing import Any
import pytest
from graphrag_storage.file_storage import FileStorage
from graphrag_storage.tables.csv_table import CSVTable
def _read_csv_rows(path: Path) -> list[dict[str, Any]]:
"""Read all rows from a CSV file as dicts."""
with path.open("r", encoding="utf-8") as f:
return list(csv.DictReader(f))
def _write_seed_csv(path: Path, rows: list[dict[str, Any]]) -> None:
"""Write seed rows to a CSV file for test setup."""
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
class TestCSVTableTruncateWrite:
"""Verify the temp-file write strategy when truncate=True."""
@pytest.fixture
def storage(self, tmp_path: Path) -> FileStorage:
"""Create a FileStorage rooted at a temp directory."""
return FileStorage(base_dir=str(tmp_path))
@pytest.fixture
def seed_file(
self,
storage: FileStorage,
tmp_path: Path,
) -> Path:
"""Seed a text_units.csv file with original data."""
rows = [
{"id": "tu1", "text": "original1"},
{"id": "tu2", "text": "original2"},
]
file_path = tmp_path / "text_units.csv"
_write_seed_csv(file_path, rows)
return file_path
async def test_original_readable_during_writes(
self,
storage: FileStorage,
seed_file: Path,
):
"""The original file remains intact while writes go to a temp file."""
table = CSVTable(storage, "text_units", truncate=True)
await table.write({"id": "tu_new", "text": "replaced"})
original_rows = _read_csv_rows(seed_file)
assert len(original_rows) == 2
assert original_rows[0]["id"] == "tu1"
assert original_rows[1]["id"] == "tu2"
await table.close()
async def test_temp_file_replaces_original_on_close(
self,
storage: FileStorage,
seed_file: Path,
):
"""After close(), the original file contains only the new data."""
table = CSVTable(storage, "text_units", truncate=True)
await table.write({"id": "tu_new", "text": "replaced"})
await table.close()
rows = _read_csv_rows(seed_file)
assert len(rows) == 1
assert rows[0]["id"] == "tu_new"
assert rows[0]["text"] == "replaced"
async def test_no_temp_file_left_after_close(
self,
storage: FileStorage,
seed_file: Path,
):
"""No leftover temp files in the directory after close()."""
table = CSVTable(storage, "text_units", truncate=True)
await table.write({"id": "tu1", "text": "new"})
await table.close()
csv_files = list(seed_file.parent.glob("*.csv"))
assert len(csv_files) == 1
assert csv_files[0].name == "text_units.csv"
async def test_multiple_writes_accumulate_in_temp(
self,
storage: FileStorage,
seed_file: Path,
):
"""Multiple rows written before close() all appear in final file."""
table = CSVTable(storage, "text_units", truncate=True)
for i in range(5):
await table.write({"id": f"tu{i}", "text": f"row{i}"})
await table.close()
rows = _read_csv_rows(seed_file)
assert len(rows) == 5
assert [r["id"] for r in rows] == [
"tu0",
"tu1",
"tu2",
"tu3",
"tu4",
]
async def test_concurrent_read_and_write_same_file(
self,
storage: FileStorage,
seed_file: Path,
):
"""Simulates the create_final_text_units pattern: read from
original while writing new rows, then close replaces the file."""
reader = CSVTable(storage, "text_units", truncate=False)
writer = CSVTable(storage, "text_units", truncate=True)
original_rows: list[dict[str, Any]] = []
async for row in reader:
original_rows.append(row)
await writer.write({
"id": row["id"],
"text": row["text"].upper(),
})
assert len(original_rows) == 2
file_during_write = _read_csv_rows(seed_file)
assert len(file_during_write) == 2
assert file_during_write[0]["text"] == "original1"
await writer.close()
await reader.close()
final_rows = _read_csv_rows(seed_file)
assert len(final_rows) == 2
assert final_rows[0]["text"] == "ORIGINAL1"
assert final_rows[1]["text"] == "ORIGINAL2"
class TestCSVTableAppendWrite:
"""Verify append behavior when truncate=False."""
@pytest.fixture
def storage(self, tmp_path: Path) -> FileStorage:
"""Create a FileStorage rooted at a temp directory."""
return FileStorage(base_dir=str(tmp_path))
async def test_append_to_existing_file(
self,
storage: FileStorage,
tmp_path: Path,
):
"""Appending to an existing file adds rows without header."""
file_path = tmp_path / "data.csv"
_write_seed_csv(file_path, [{"id": "r1", "val": "a"}])
table = CSVTable(storage, "data", truncate=False)
await table.write({"id": "r2", "val": "b"})
await table.close()
rows = _read_csv_rows(file_path)
assert len(rows) == 2
assert rows[0]["id"] == "r1"
assert rows[1]["id"] == "r2"
async def test_append_creates_file_with_header(
self,
storage: FileStorage,
tmp_path: Path,
):
"""Appending to a non-existent file creates it with header."""
table = CSVTable(storage, "new_table", truncate=False)
await table.write({"id": "r1", "val": "x"})
await table.close()
file_path = tmp_path / "new_table.csv"
rows = _read_csv_rows(file_path)
assert len(rows) == 1
assert rows[0]["id"] == "r1"
async def test_no_temp_file_used_for_append(
self,
storage: FileStorage,
tmp_path: Path,
):
"""Append mode writes directly, no temp file involved."""
table = CSVTable(storage, "direct", truncate=False)
await table.write({"id": "r1"})
csv_files = list(tmp_path.glob("*.csv"))
assert len(csv_files) == 1
assert csv_files[0].name == "direct.csv"
await table.close()
class TestCSVTableCloseIdempotent:
"""Verify close() can be called multiple times safely."""
@pytest.fixture
def storage(self, tmp_path: Path) -> FileStorage:
"""Create a FileStorage rooted at a temp directory."""
return FileStorage(base_dir=str(tmp_path))
async def test_double_close_is_safe(
self,
storage: FileStorage,
tmp_path: Path,
):
"""Calling close() twice does not raise."""
table = CSVTable(storage, "test", truncate=True)
await table.write({"id": "r1"})
await table.close()
await table.close()
async def test_close_without_writes_is_safe(
self,
storage: FileStorage,
):
"""Closing a table that was never written to is a no-op."""
table = CSVTable(storage, "empty", truncate=True)
await table.close()
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/storage/test_csv_table.py",
"license": "MIT License",
"lines": 196,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/indexing/test_cluster_graph.py | # Copyright (C) 2026 Microsoft
"""Tests for the cluster_graph operation.
These tests pin down the behavior of cluster_graph and its internal
_compute_leiden_communities function so that refactoring (vectorizing
iterrows, reducing copies, etc.) can be verified against known output.
"""
import pandas as pd
import pytest
from graphrag.index.operations.cluster_graph import (
Communities,
cluster_graph,
)
def _make_edges(
rows: list[tuple[str, str, float]],
) -> pd.DataFrame:
"""Build a minimal relationships DataFrame from (source, target, weight)."""
return pd.DataFrame([{"source": s, "target": t, "weight": w} for s, t, w in rows])
def _node_sets(clusters: Communities) -> list[set[str]]:
"""Extract sorted-by-level list of node sets from cluster output."""
return [set(nodes) for _, _, _, nodes in clusters]
# -------------------------------------------------------------------
# Basic clustering
# -------------------------------------------------------------------
class TestClusterGraphBasic:
"""Verify basic clustering on small synthetic graphs."""
def test_single_triangle(self):
"""A single triangle should produce one community at level 0."""
edges = _make_edges([("X", "Y", 1.0), ("X", "Z", 1.0), ("Y", "Z", 1.0)])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
assert len(clusters) == 1
level, _cid, parent, nodes = clusters[0]
assert level == 0
assert parent == -1
assert set(nodes) == {"X", "Y", "Z"}
def test_two_disconnected_cliques(self):
"""Two disconnected triangles should produce two communities."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
assert len(clusters) == 2
node_sets = _node_sets(clusters)
assert {"A", "B", "C"} in node_sets
assert {"D", "E", "F"} in node_sets
for level, _, parent, _ in clusters:
assert level == 0
assert parent == -1
def test_lcc_filters_to_largest_component(self):
"""With use_lcc=True, only the largest connected component is kept."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=True, seed=42)
assert len(clusters) == 1
all_nodes = set(clusters[0][3])
assert len(all_nodes) == 3
# -------------------------------------------------------------------
# Edge normalization
# -------------------------------------------------------------------
class TestEdgeNormalization:
"""Verify that direction normalization and deduplication work."""
def test_reversed_edges_produce_same_result(self):
"""Reversing all edge directions should yield identical clusters."""
forward = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
backward = _make_edges([
("B", "A", 1.0),
("C", "A", 1.0),
("C", "B", 1.0),
("E", "D", 1.0),
("F", "D", 1.0),
("F", "E", 1.0),
])
clusters_fwd = cluster_graph(
forward, max_cluster_size=10, use_lcc=False, seed=42
)
clusters_bwd = cluster_graph(
backward, max_cluster_size=10, use_lcc=False, seed=42
)
assert _node_sets(clusters_fwd) == _node_sets(clusters_bwd)
def test_duplicate_edges_are_deduped(self):
"""A→B and B→A should be treated as one edge after normalization."""
edges = _make_edges([
("A", "B", 1.0),
("B", "A", 2.0),
("A", "C", 1.0),
("B", "C", 1.0),
])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
assert len(clusters) == 1
assert set(clusters[0][3]) == {"A", "B", "C"}
def test_missing_weight_defaults_to_one(self):
"""Edges without a weight column should default to weight 1.0."""
edges = pd.DataFrame({
"source": ["A", "A", "B"],
"target": ["B", "C", "C"],
})
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
assert len(clusters) == 1
assert set(clusters[0][3]) == {"A", "B", "C"}
# -------------------------------------------------------------------
# Determinism
# -------------------------------------------------------------------
class TestDeterminism:
"""Verify that seeding produces reproducible results."""
def test_same_seed_same_result(self):
"""Identical seed should yield identical output."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
c1 = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=123)
c2 = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=123)
assert c1 == c2
def test_does_not_mutate_input(self):
"""cluster_graph should not modify the input DataFrame."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
])
original = edges.copy()
cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
pd.testing.assert_frame_equal(edges, original)
# -------------------------------------------------------------------
# Output structure
# -------------------------------------------------------------------
class TestOutputStructure:
"""Verify the shape and types of the Communities output."""
def test_output_tuple_structure(self):
"""Each entry should be (level, community_id, parent, node_list)."""
edges = _make_edges([("A", "B", 1.0), ("A", "C", 1.0), ("B", "C", 1.0)])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
for entry in clusters:
assert len(entry) == 4
level, cid, parent, nodes = entry
assert isinstance(level, int)
assert isinstance(cid, int)
assert isinstance(parent, int)
assert isinstance(nodes, list)
assert all(isinstance(n, str) for n in nodes)
def test_level_zero_has_parent_minus_one(self):
"""All level-0 clusters should have parent == -1."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
for level, _, parent, _ in clusters:
if level == 0:
assert parent == -1
def test_all_nodes_covered_at_each_level(self):
"""At any given level, the union of all community nodes should
equal exactly the set of all nodes in the graph for that level."""
edges = _make_edges([
("A", "B", 1.0),
("A", "C", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("D", "F", 1.0),
("E", "F", 1.0),
])
clusters = cluster_graph(edges, max_cluster_size=10, use_lcc=False, seed=42)
levels: dict[int, set[str]] = {}
for level, _, _, nodes in clusters:
levels.setdefault(level, set()).update(nodes)
all_nodes = {"A", "B", "C", "D", "E", "F"}
for level, covered_nodes in levels.items():
assert covered_nodes == all_nodes, (
f"Level {level}: expected {all_nodes}, got {covered_nodes}"
)
# -------------------------------------------------------------------
# Real test data (golden file regression)
# -------------------------------------------------------------------
class TestClusterGraphRealData:
"""Regression tests using the shared test fixture data."""
@pytest.fixture
def relationships(self) -> pd.DataFrame:
"""Load the test relationships fixture."""
return pd.read_parquet("tests/verbs/data/relationships.parquet")
def test_cluster_count(self, relationships: pd.DataFrame):
"""Pin the expected number of clusters from the fixture data."""
clusters = cluster_graph(
relationships,
max_cluster_size=10,
use_lcc=True,
seed=0xDEADBEEF,
)
assert len(clusters) == 122
def test_level_distribution(self, relationships: pd.DataFrame):
"""Pin the expected number of clusters per level."""
clusters = cluster_graph(
relationships,
max_cluster_size=10,
use_lcc=True,
seed=0xDEADBEEF,
)
from collections import Counter
level_counts = Counter(c[0] for c in clusters)
assert level_counts == {0: 23, 1: 65, 2: 32, 3: 2}
def test_level_zero_nodes_sample(self, relationships: pd.DataFrame):
"""Spot-check a few known nodes in level-0 clusters."""
clusters = cluster_graph(
relationships,
max_cluster_size=10,
use_lcc=True,
seed=0xDEADBEEF,
)
level_0 = [c for c in clusters if c[0] == 0]
all_level_0_nodes = set()
for _, _, _, nodes in level_0:
all_level_0_nodes.update(nodes)
assert "SCROOGE" in all_level_0_nodes
assert "ABRAHAM" in all_level_0_nodes
assert "JACOB MARLEY" in all_level_0_nodes
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/test_cluster_graph.py",
"license": "MIT License",
"lines": 239,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/indexing/test_create_communities.py | # Copyright (C) 2026 Microsoft
"""Tests for the create_communities pure function.
These tests pin down the behavior of the create_communities function
independently of the workflow runner, so that refactoring (vectorizing
the per-level loop, streaming entity reads, streaming writes, etc.)
can be verified against known output.
"""
import uuid
from typing import Any
import numpy as np
import pandas as pd
import pytest
from graphrag.data_model.schemas import COMMUNITIES_FINAL_COLUMNS
from graphrag.index.workflows.create_communities import (
_sanitize_row,
create_communities,
)
from graphrag_storage.tables.csv_table import CSVTable
from graphrag_storage.tables.table import Table
class FakeTable(CSVTable):
"""In-memory table that collects written rows for test assertions."""
def __init__(self) -> None:
self.rows: list[dict[str, Any]] = []
async def write(self, row: dict[str, Any]) -> None:
"""Append a row to the in-memory store."""
self.rows.append(row)
class FakeEntitiesTable(Table):
"""In-memory read-only table that supports async iteration."""
def __init__(self, rows: list[dict[str, Any]]) -> None:
self._rows = rows
self._index = 0
def __aiter__(self):
"""Return an async iterator over the rows."""
self._index = 0
return self
async def __anext__(self) -> dict[str, Any]:
"""Yield the next row or stop."""
if self._index >= len(self._rows):
raise StopAsyncIteration
row = self._rows[self._index]
self._index += 1
return row
async def length(self) -> int:
"""Return number of rows."""
return len(self._rows)
async def has(self, row_id: str) -> bool:
"""Check if a row with the given ID exists."""
return any(r.get("id") == row_id for r in self._rows)
async def write(self, row: dict[str, Any]) -> None:
"""Not supported for read-only table."""
raise NotImplementedError
async def close(self) -> None:
"""No-op."""
async def _run_create_communities(
title_to_entity_id: dict[str, str],
relationships: pd.DataFrame,
**kwargs: Any,
) -> pd.DataFrame:
"""Helper that runs create_communities with fake tables and returns all rows as a DataFrame."""
communities_table = FakeTable()
entity_rows = [
{"id": eid, "title": title} for title, eid in title_to_entity_id.items()
]
entities_table = FakeEntitiesTable(entity_rows)
await create_communities(communities_table, entities_table, relationships, **kwargs)
return pd.DataFrame(communities_table.rows)
def _make_title_to_entity_id(
rows: list[tuple[str, str]],
) -> dict[str, str]:
"""Build a title-to-entity-id mapping from (id, title) pairs."""
return {title: eid for eid, title in rows}
def _make_relationships(
rows: list[tuple[str, str, str, float, list[str]]],
) -> pd.DataFrame:
"""Build a minimal relationships DataFrame.
Each row is (id, source, target, weight, text_unit_ids).
"""
return pd.DataFrame([
{
"id": rid,
"source": src,
"target": tgt,
"weight": w,
"text_unit_ids": tuids,
"human_readable_id": i,
}
for i, (rid, src, tgt, w, tuids) in enumerate(rows)
])
@pytest.fixture
def two_triangles():
"""Two disconnected triangles: {A,B,C} and {D,E,F}."""
title_to_entity_id = _make_title_to_entity_id([
("e1", "A"),
("e2", "B"),
("e3", "C"),
("e4", "D"),
("e5", "E"),
("e6", "F"),
])
relationships = _make_relationships([
("r1", "A", "B", 1.0, ["t1"]),
("r2", "A", "C", 1.0, ["t1", "t2"]),
("r3", "B", "C", 1.0, ["t2"]),
("r4", "D", "E", 1.0, ["t3"]),
("r5", "D", "F", 1.0, ["t3", "t4"]),
("r6", "E", "F", 1.0, ["t4"]),
])
return title_to_entity_id, relationships
# -------------------------------------------------------------------
# Column schema
# -------------------------------------------------------------------
class TestOutputSchema:
"""Verify the output DataFrame has the expected column schema."""
async def test_has_all_final_columns(self, two_triangles):
"""Output must have exactly the COMMUNITIES_FINAL_COLUMNS."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
assert list(result.columns) == COMMUNITIES_FINAL_COLUMNS
async def test_column_order_matches_schema(self, two_triangles):
"""Column order must match the schema constant exactly."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for i, col_name in enumerate(COMMUNITIES_FINAL_COLUMNS):
assert result.columns[i] == col_name
# -------------------------------------------------------------------
# Metadata fields
# -------------------------------------------------------------------
class TestMetadataFields:
"""Verify computed metadata fields like id, title, size, period."""
async def test_uuid_ids(self, two_triangles):
"""Each community id should be a valid UUID4."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
parsed = uuid.UUID(row["id"])
assert parsed.version == 4
async def test_title_format(self, two_triangles):
"""Title should be 'Community N' where N is the community id."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
assert row["title"] == f"Community {row['community']}"
async def test_human_readable_id_equals_community(self, two_triangles):
"""human_readable_id should equal the community integer id."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
assert (result["human_readable_id"] == result["community"]).all()
async def test_size_equals_entity_count(self, two_triangles):
"""size should equal the length of entity_ids."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
assert row["size"] == len(row["entity_ids"])
async def test_period_is_iso_date(self, two_triangles):
"""period should be a valid ISO date string."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
from datetime import date
for _, row in result.iterrows():
date.fromisoformat(row["period"])
# -------------------------------------------------------------------
# Entity aggregation
# -------------------------------------------------------------------
class TestEntityAggregation:
"""Verify that entity_ids are correctly aggregated per community."""
async def test_entity_ids_per_community(self, two_triangles):
"""Each community should contain exactly the entities matching
its cluster nodes."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
comm_0 = result[result["community"] == 0].iloc[0]
comm_1 = result[result["community"] == 1].iloc[0]
assert sorted(comm_0["entity_ids"]) == ["e1", "e2", "e3"]
assert sorted(comm_1["entity_ids"]) == ["e4", "e5", "e6"]
async def test_entity_ids_are_lists(self, two_triangles):
"""entity_ids should be Python lists, not numpy arrays."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
assert isinstance(row["entity_ids"], list)
# -------------------------------------------------------------------
# Relationship and text_unit aggregation
# -------------------------------------------------------------------
class TestRelationshipAggregation:
"""Verify that relationship_ids and text_unit_ids are correctly
aggregated (intra-community only) and deduplicated."""
async def test_relationship_ids_per_community(self, two_triangles):
"""Each community should only include relationships where both
endpoints are in the same community."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
comm_0 = result[result["community"] == 0].iloc[0]
comm_1 = result[result["community"] == 1].iloc[0]
assert sorted(comm_0["relationship_ids"]) == ["r1", "r2", "r3"]
assert sorted(comm_1["relationship_ids"]) == ["r4", "r5", "r6"]
async def test_text_unit_ids_per_community(self, two_triangles):
"""text_unit_ids should be the deduplicated union of text units
from the community's intra-community relationships."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
comm_0 = result[result["community"] == 0].iloc[0]
comm_1 = result[result["community"] == 1].iloc[0]
assert sorted(comm_0["text_unit_ids"]) == ["t1", "t2"]
assert sorted(comm_1["text_unit_ids"]) == ["t3", "t4"]
async def test_lists_are_sorted_and_deduplicated(self, two_triangles):
"""relationship_ids and text_unit_ids should be sorted with
no duplicates."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
assert row["relationship_ids"] == sorted(set(row["relationship_ids"]))
assert row["text_unit_ids"] == sorted(set(row["text_unit_ids"]))
async def test_cross_community_relationships_excluded(self):
"""A relationship spanning two communities must not appear in
either community's relationship_ids."""
title_to_entity_id = _make_title_to_entity_id([
("e1", "A"),
("e2", "B"),
("e3", "C"),
("e4", "D"),
("e5", "E"),
("e6", "F"),
])
relationships = _make_relationships([
("r1", "A", "B", 1.0, ["t1"]),
("r2", "A", "C", 1.0, ["t1"]),
("r3", "B", "C", 1.0, ["t1"]),
("r_cross", "C", "D", 0.1, ["t_cross"]),
("r4", "D", "E", 1.0, ["t2"]),
("r5", "D", "F", 1.0, ["t2"]),
("r6", "E", "F", 1.0, ["t2"]),
])
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
all_rel_ids = []
for _, row in result.iterrows():
all_rel_ids.extend(row["relationship_ids"])
assert "r_cross" not in all_rel_ids
assert "t_cross" not in [
tid for _, row in result.iterrows() for tid in row["text_unit_ids"]
]
# -------------------------------------------------------------------
# Parent / children tree
# -------------------------------------------------------------------
class TestParentChildTree:
"""Verify the parent-child tree structure is consistent."""
async def test_level_zero_parent_is_minus_one(self, two_triangles):
"""All level-0 communities should have parent == -1."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
lvl0 = result[result["level"] == 0]
assert (lvl0["parent"] == -1).all()
async def test_leaf_communities_have_empty_children(self, two_triangles):
"""Communities that are nobody's parent should have children=[]."""
title_to_entity_id, relationships = two_triangles
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
for _, row in result.iterrows():
children = row["children"]
if isinstance(children, list) and len(children) == 0:
child_rows = result[result["parent"] == row["community"]]
assert len(child_rows) == 0
async def test_parent_child_bidirectional_consistency_real_data(self):
"""For real test data: if community X lists Y as child,
then Y's parent must be X."""
entities_df = pd.read_parquet("tests/verbs/data/entities.parquet")
title_to_entity_id = dict(
zip(entities_df["title"], entities_df["id"], strict=False)
)
relationships = pd.read_parquet("tests/verbs/data/relationships.parquet")
result = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=True,
seed=0xDEADBEEF,
)
for _, row in result.iterrows():
children = row["children"]
if hasattr(children, "__len__") and len(children) > 0:
for child_id in children:
child_row = result[result["community"] == child_id]
assert len(child_row) == 1, (
f"Child {child_id} not found or duplicated"
)
assert child_row.iloc[0]["parent"] == row["community"]
# -------------------------------------------------------------------
# LCC filtering
# -------------------------------------------------------------------
class TestLccFiltering:
"""Verify LCC filtering interaction with create_communities."""
async def test_lcc_reduces_community_count(self):
"""With use_lcc=True and two disconnected components, only the
larger component's communities should appear."""
title_to_entity_id = _make_title_to_entity_id([
("e1", "A"),
("e2", "B"),
("e3", "C"),
("e4", "D"),
("e5", "E"),
("e6", "F"),
])
relationships = _make_relationships([
("r1", "A", "B", 1.0, ["t1"]),
("r2", "A", "C", 1.0, ["t1"]),
("r3", "B", "C", 1.0, ["t1"]),
("r4", "D", "E", 1.0, ["t2"]),
("r5", "D", "F", 1.0, ["t2"]),
("r6", "E", "F", 1.0, ["t2"]),
])
result_no_lcc = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=False,
seed=42,
)
result_lcc = await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=True,
seed=42,
)
assert len(result_lcc) < len(result_no_lcc)
assert len(result_lcc) == 1
# -------------------------------------------------------------------
# Golden file regression (real test data)
# -------------------------------------------------------------------
class TestRealDataRegression:
"""Regression tests using the shared test fixture data.
These pin exact values so any behavioral change during refactoring
is caught immediately.
"""
@pytest.fixture
async def real_result(self) -> pd.DataFrame:
"""Run create_communities on the test fixture data."""
entities_df = pd.read_parquet("tests/verbs/data/entities.parquet")
title_to_entity_id = dict(
zip(entities_df["title"], entities_df["id"], strict=False)
)
relationships = pd.read_parquet("tests/verbs/data/relationships.parquet")
return await _run_create_communities(
title_to_entity_id,
relationships,
max_cluster_size=10,
use_lcc=True,
seed=0xDEADBEEF,
)
async def test_row_count(self, real_result: pd.DataFrame):
"""Pin the expected number of communities."""
assert len(real_result) == 122
async def test_level_distribution(self, real_result: pd.DataFrame):
"""Pin the expected number of communities per level."""
from collections import Counter
counts = Counter(real_result["level"].tolist())
assert counts == {0: 23, 1: 65, 2: 32, 3: 2}
async def test_values_match_golden_file(self, real_result: pd.DataFrame):
"""The output should match the golden Parquet file for all
columns except id (UUID) and period (date-dependent)."""
expected = pd.read_parquet("tests/verbs/data/communities.parquet")
assert len(real_result) == len(expected)
skip_columns = {"id", "period", "children"}
for col in COMMUNITIES_FINAL_COLUMNS:
if col in skip_columns:
continue
pd.testing.assert_series_equal(
real_result[col],
expected[col],
check_dtype=False,
check_index=False,
check_names=False,
obj=f"Column '{col}'",
)
# children requires special handling: the golden file stores
# numpy arrays, the function may return lists or arrays
for i in range(len(real_result)):
actual_children = list(real_result.iloc[i]["children"])
expected_children = list(expected.iloc[i]["children"])
assert actual_children == expected_children, (
f"Row {i} children mismatch: {actual_children} != {expected_children}"
)
async def test_communities_with_children(self, real_result: pd.DataFrame):
"""Pin the expected number of communities that have children."""
has_children = real_result["children"].apply(
lambda x: hasattr(x, "__len__") and len(x) > 0
)
assert has_children.sum() == 24
# -------------------------------------------------------------------
# Row sanitization
# -------------------------------------------------------------------
class TestSanitizeRow:
"""Verify numpy types are converted to native Python types."""
def test_ndarray_to_list(self):
"""np.ndarray values should become plain lists."""
row = {"children": np.array([1, 2, 3])}
result = _sanitize_row(row)
assert result["children"] == [1, 2, 3]
assert isinstance(result["children"], list)
def test_empty_ndarray_to_empty_list(self):
"""An empty np.ndarray should become an empty list."""
row = {"children": np.array([])}
assert _sanitize_row(row)["children"] == []
def test_np_integer_to_int(self):
"""np.integer values should become native int."""
row = {"community": np.int64(42)}
result = _sanitize_row(row)
assert result["community"] == 42
assert type(result["community"]) is int
def test_np_floating_to_float(self):
"""np.floating values should become native float."""
row = {"weight": np.float64(3.14)}
result = _sanitize_row(row)
assert result["weight"] == pytest.approx(3.14)
assert type(result["weight"]) is float
def test_native_types_pass_through(self):
"""Native Python types should pass through unchanged."""
row = {"id": "abc", "size": 5, "tags": ["a", "b"]}
assert _sanitize_row(row) == row
def test_mixed_row(self):
"""A row with a mix of numpy and native types."""
row = {
"community": np.int64(7),
"children": np.array([1, 2]),
"title": "Community 7",
"weight": np.float64(0.5),
}
result = _sanitize_row(row)
assert result == {
"community": 7,
"children": [1, 2],
"title": "Community 7",
"weight": pytest.approx(0.5),
}
assert type(result["community"]) is int
assert type(result["children"]) is list
assert type(result["weight"]) is float
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/test_create_communities.py",
"license": "MIT License",
"lines": 525,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/csv_table.py | # Copyright (c) 2025 Microsoft Corporation.
# Licensed under the MIT Licenses
"""A CSV-based implementation of the Table abstraction for streaming row access."""
from __future__ import annotations
import csv
import inspect
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any
import aiofiles
from graphrag_storage.file_storage import FileStorage
from graphrag_storage.tables.table import RowTransformer, Table
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from io import TextIOWrapper
from graphrag_storage import Storage
try:
csv.field_size_limit(sys.maxsize)
except OverflowError:
csv.field_size_limit(100 * 1024 * 1024)
def _identity(row: dict[str, Any]) -> Any:
"""Return row unchanged (default transformer)."""
return row
def _apply_transformer(transformer: RowTransformer, row: dict[str, Any]) -> Any:
"""Apply transformer to row, handling both callables and classes.
If transformer is a class (e.g., Pydantic model), calls it with **row.
Otherwise calls it with row as positional argument.
"""
if inspect.isclass(transformer):
return transformer(**row)
return transformer(row)
class CSVTable(Table):
"""Row-by-row streaming interface for CSV tables."""
def __init__(
self,
storage: Storage,
table_name: str,
transformer: RowTransformer | None = None,
truncate: bool = True,
encoding: str = "utf-8",
):
"""Initialize with storage backend and table name.
Args:
storage: Storage instance (File, Blob, or Cosmos)
table_name: Name of the table (e.g., "documents")
transformer: Optional callable to transform each row before
yielding. Receives a dict, returns a transformed dict.
Defaults to identity (no transformation).
truncate: If True (default), writes go to a temporary file
which is moved over the original on close(). This allows
safe concurrent reads from the original while writes
accumulate. If False, append to existing file.
encoding: Character encoding for reading/writing CSV files.
Defaults to "utf-8".
"""
self._storage = storage
self._table_name = table_name
self._file_key = f"{table_name}.csv"
self._transformer = transformer or _identity
self._truncate = truncate
self._encoding = encoding
self._write_file: TextIOWrapper | None = None
self._writer: csv.DictWriter | None = None
self._header_written = False
self._temp_path: Path | None = None
self._final_path: Path | None = None
def __aiter__(self) -> AsyncIterator[Any]:
"""Iterate through rows one at a time.
The transformer is applied to each row before yielding.
If transformer is a Pydantic model, yields model instances.
Yields
------
Any:
Each row as dict or transformed type (e.g., Pydantic model).
"""
return self._aiter_impl()
async def _aiter_impl(self) -> AsyncIterator[Any]:
"""Implement async iteration over rows."""
if isinstance(self._storage, FileStorage):
file_path = self._storage.get_path(self._file_key)
with Path.open(file_path, "r", encoding=self._encoding) as f:
reader = csv.DictReader(f)
for row in reader:
yield _apply_transformer(self._transformer, row)
async def length(self) -> int:
"""Return the number of rows in the table."""
if isinstance(self._storage, FileStorage):
file_path = self._storage.get_path(self._file_key)
count = 0
async with aiofiles.open(file_path, "rb") as f:
while True:
chunk = await f.read(65536)
if not chunk:
break
count += chunk.count(b"\n")
return count - 1
return 0
async def has(self, row_id: str) -> bool:
"""Check if row with given ID exists."""
async for row in self:
# Handle both dict and object (e.g., Pydantic model)
if isinstance(row, dict):
if row.get("id") == row_id:
return True
elif getattr(row, "id", None) == row_id:
return True
return False
async def write(self, row: dict[str, Any]) -> None:
"""Write a single row to the CSV file.
On first write, opens a file handle. When truncate=True, writes
go to a temporary file in the same directory; the temp file is
moved over the original in close(), making it safe to read from
the original while writes are in progress. When truncate=False,
rows are appended directly to the existing file.
Args
----
row: Dictionary representing a single row to write.
"""
if isinstance(self._storage, FileStorage) and self._write_file is None:
file_path = self._storage.get_path(self._file_key)
file_path.parent.mkdir(parents=True, exist_ok=True)
if self._truncate:
fd, tmp = tempfile.mkstemp(
suffix=".csv",
dir=file_path.parent,
)
os.close(fd)
self._temp_path = Path(tmp)
self._final_path = file_path
self._write_file = Path.open(
self._temp_path,
"w",
encoding=self._encoding,
newline="",
)
write_header = True
else:
file_exists = file_path.exists() and file_path.stat().st_size > 0
write_header = not file_exists
self._write_file = Path.open(
file_path,
"a",
encoding=self._encoding,
newline="",
)
self._writer = csv.DictWriter(
self._write_file,
fieldnames=list(row.keys()),
)
if write_header:
self._writer.writeheader()
self._header_written = write_header
if self._writer is not None:
self._writer.writerow(row)
async def close(self) -> None:
"""Flush buffered writes and release resources.
When truncate=True, the temp file is moved over the original
so that readers never see a partially-written file.
"""
if self._write_file is not None:
self._write_file.close()
self._write_file = None
self._writer = None
self._header_written = False
if self._temp_path is not None and self._final_path is not None:
shutil.move(str(self._temp_path), str(self._final_path))
self._temp_path = None
self._final_path = None
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/csv_table.py",
"license": "MIT License",
"lines": 171,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/parquet_table.py | # Copyright (C) 2025 Microsoft
# Licensed under the MIT License
"""A Parquet-based implementation of the Table abstraction with simulated streaming."""
from __future__ import annotations
import inspect
from io import BytesIO
from typing import TYPE_CHECKING, Any, cast
import pandas as pd
from graphrag_storage.tables.table import RowTransformer, Table
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from graphrag_storage.storage import Storage
def _identity(row: dict[str, Any]) -> Any:
"""Return row unchanged (default transformer)."""
return row
def _apply_transformer(transformer: RowTransformer, row: dict[str, Any]) -> Any:
"""Apply transformer to row, handling both callables and classes.
If transformer is a class (e.g., Pydantic model), calls it with **row.
Otherwise calls it with row as positional argument.
"""
if inspect.isclass(transformer):
return transformer(**row)
return transformer(row)
class ParquetTable(Table):
"""Simulated streaming interface for Parquet tables.
Parquet format doesn't support true row-by-row streaming, so this
implementation simulates streaming via:
- Read: Loads DataFrame, yields rows via iterrows()
- Write: Accumulates rows in memory, writes all at once on close()
This provides API compatibility with CSVTable while maintaining
Parquet's performance characteristics for bulk operations.
"""
def __init__(
self,
storage: Storage,
table_name: str,
transformer: RowTransformer | None = None,
truncate: bool = True,
):
"""Initialize with storage backend and table name.
Args:
storage: Storage instance (File, Blob, or Cosmos)
table_name: Name of the table (e.g., "documents")
transformer: Optional callable to transform each row before
yielding. Receives a dict, returns a transformed dict.
Defaults to identity (no transformation).
truncate: If True (default), overwrite file on close.
If False, append to existing file.
"""
self._storage = storage
self._table_name = table_name
self._file_key = f"{table_name}.parquet"
self._transformer = transformer or _identity
self._truncate = truncate
self._df: pd.DataFrame | None = None
self._write_rows: list[dict[str, Any]] = []
def __aiter__(self) -> AsyncIterator[Any]:
"""Iterate through rows one at a time.
Loads the entire DataFrame on first iteration, then yields rows
one at a time with the transformer applied.
Yields
------
Any:
Each row as dict or transformed type (e.g., Pydantic model).
"""
return self._aiter_impl()
async def _aiter_impl(self) -> AsyncIterator[Any]:
"""Implement async iteration over rows."""
if self._df is None:
if await self._storage.has(self._file_key):
data = await self._storage.get(self._file_key, as_bytes=True)
self._df = pd.read_parquet(BytesIO(data))
else:
self._df = pd.DataFrame()
for _, row in self._df.iterrows():
row_dict = cast("dict[str, Any]", row.to_dict())
yield _apply_transformer(self._transformer, row_dict)
async def length(self) -> int:
"""Return the number of rows in the table."""
if self._df is None:
if await self._storage.has(self._file_key):
data = await self._storage.get(self._file_key, as_bytes=True)
self._df = pd.read_parquet(BytesIO(data))
else:
return 0
return len(self._df)
async def has(self, row_id: str) -> bool:
"""Check if row with given ID exists."""
async for row in self:
if isinstance(row, dict):
if row.get("id") == row_id:
return True
elif getattr(row, "id", None) == row_id:
return True
return False
async def write(self, row: dict[str, Any]) -> None:
"""Accumulate a single row for later batch write.
Rows are stored in memory and written to Parquet format
when close() is called.
Args
----
row: Dictionary representing a single row to write.
"""
self._write_rows.append(row)
async def close(self) -> None:
"""Flush accumulated rows to Parquet file and release resources.
Converts all accumulated rows to a DataFrame and writes
to storage as a Parquet file. If truncate=False and file exists,
appends to existing data.
"""
if self._write_rows:
new_df = pd.DataFrame(self._write_rows)
if not self._truncate and await self._storage.has(self._file_key):
existing_data = await self._storage.get(self._file_key, as_bytes=True)
existing_df = pd.read_parquet(BytesIO(existing_data))
new_df = pd.concat([existing_df, new_df], ignore_index=True)
await self._storage.set(self._file_key, new_df.to_parquet())
self._write_rows = []
self._df = None
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/parquet_table.py",
"license": "MIT License",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/table.py | # Copyright (C) 2025 Microsoft
# Licensed under the MIT License
"""Table abstraction for streaming row-by-row access."""
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Callable
from types import TracebackType
from typing import Any
from typing_extensions import Self
RowTransformer = Callable[[dict[str, Any]], Any]
class Table(ABC):
"""Abstract base class for streaming table access.
Provides row-by-row iteration and write capabilities for memory-efficient
processing of large datasets. Supports async context manager protocol for
automatic resource cleanup.
Examples
--------
Reading rows as dicts:
>>> async with (
... provider.open(
... "documents"
... ) as table
... ):
... async for (
... row
... ) in table:
... process(row)
With Pydantic model as transformer:
>>> async with (
... provider.open(
... "entities",
... Entity,
... ) as table
... ):
... async for entity in table: # yields Entity instances
... print(
... entity.name
... )
"""
@abstractmethod
def __aiter__(self) -> AsyncIterator[Any]:
"""Yield rows asynchronously, transformed if transformer provided.
Yields
------
Any:
Each row, either as dict or transformed type (e.g., Pydantic model).
"""
...
@abstractmethod
async def length(self) -> int:
"""Return number of rows asynchronously.
Returns
-------
int:
Number of rows in the table.
"""
@abstractmethod
async def has(self, row_id: str) -> bool:
"""Check if a row with the given ID exists.
Args
----
row_id: The ID value to search for.
Returns
-------
bool:
True if a row with matching ID exists.
"""
@abstractmethod
async def write(self, row: dict[str, Any]) -> None:
"""Write a single row to the table.
Args
----
row: Dictionary representing a single row to write.
"""
@abstractmethod
async def close(self) -> None:
"""Flush buffered writes and release resources.
This method is called automatically when exiting the async context
manager, but can also be called explicitly.
"""
async def __aenter__(self) -> Self:
"""Enter async context manager.
Returns
-------
Table:
Self for context manager usage.
"""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Exit async context manager, ensuring close() is called.
Args
----
exc_type: Exception type if an exception occurred
exc_val: Exception value if an exception occurred
exc_tb: Exception traceback if an exception occurred
"""
await self.close()
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/table.py",
"license": "MIT License",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/prompt_tune/test_load_docs_in_chunks.py | # Copyright (C) 2025 Microsoft
# Licensed under the MIT License
"""Unit tests for load_docs_in_chunks function."""
import logging
from dataclasses import dataclass
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from graphrag.prompt_tune.loader.input import load_docs_in_chunks
from graphrag.prompt_tune.types import DocSelectionType
@dataclass
class MockTextDocument:
"""Mock TextDocument for testing."""
id: str
text: str
title: str
creation_date: str
raw_data: dict[str, Any] | None = None
class MockTokenizer:
"""Mock tokenizer for testing."""
def encode(self, text: str) -> list[int]:
"""Encode text to tokens (simple char-based)."""
return [ord(c) for c in text]
def decode(self, tokens: list[int]) -> str:
"""Decode tokens to text."""
return "".join(chr(t) for t in tokens)
@dataclass
class MockChunk:
"""Mock chunk result."""
text: str
class MockChunker:
"""Mock chunker for testing."""
def chunk(self, text: str, transform: Any = None) -> list[MockChunk]:
"""Split text into sentence-like chunks."""
sentences = [s.strip() for s in text.split(".") if s.strip()]
return [MockChunk(text=s + ".") for s in sentences]
class MockEmbeddingModel:
"""Mock embedding model for testing."""
def __init__(self):
"""Initialize with mock tokenizer."""
self.tokenizer = MockTokenizer()
@pytest.fixture
def mock_config():
"""Create a mock GraphRagConfig."""
config = MagicMock()
config.embed_text.embedding_model_id = "test-model"
config.embed_text.batch_size = 10
config.embed_text.batch_max_tokens = 1000
config.concurrent_requests = 1
config.get_embedding_model_config.return_value = MagicMock()
return config
@pytest.fixture
def mock_logger():
"""Create a mock logger."""
return logging.getLogger("test")
@pytest.fixture
def sample_documents():
"""Create sample documents for testing."""
return [
MockTextDocument(
id="doc1",
text="First sentence. Second sentence. Third sentence.",
title="Doc 1",
creation_date="2025-01-01",
),
MockTextDocument(
id="doc2",
text="Another document. With content.",
title="Doc 2",
creation_date="2025-01-02",
),
]
class TestLoadDocsInChunks:
"""Tests for load_docs_in_chunks function."""
@pytest.mark.asyncio
async def test_top_selection_returns_limited_chunks(
self, mock_config, mock_logger, sample_documents
):
"""Test TOP selection method returns the first N chunks."""
mock_reader = AsyncMock()
mock_reader.read_files.return_value = sample_documents
with (
patch(
"graphrag.prompt_tune.loader.input.create_embedding",
return_value=MockEmbeddingModel(),
),
patch(
"graphrag.prompt_tune.loader.input.create_storage",
return_value=MagicMock(),
),
patch(
"graphrag.prompt_tune.loader.input.create_input_reader",
return_value=mock_reader,
),
patch(
"graphrag.prompt_tune.loader.input.create_chunker",
return_value=MockChunker(),
),
):
result = await load_docs_in_chunks(
config=mock_config,
select_method=DocSelectionType.TOP,
limit=2,
logger=mock_logger,
)
assert len(result) == 2
assert result[0] == "First sentence."
assert result[1] == "Second sentence."
@pytest.mark.asyncio
async def test_random_selection_returns_correct_count(
self, mock_config, mock_logger, sample_documents
):
"""Test RANDOM selection method returns the correct number of chunks."""
mock_reader = AsyncMock()
mock_reader.read_files.return_value = sample_documents
with (
patch(
"graphrag.prompt_tune.loader.input.create_embedding",
return_value=MockEmbeddingModel(),
),
patch(
"graphrag.prompt_tune.loader.input.create_storage",
return_value=MagicMock(),
),
patch(
"graphrag.prompt_tune.loader.input.create_input_reader",
return_value=mock_reader,
),
patch(
"graphrag.prompt_tune.loader.input.create_chunker",
return_value=MockChunker(),
),
):
result = await load_docs_in_chunks(
config=mock_config,
select_method=DocSelectionType.RANDOM,
limit=3,
logger=mock_logger,
)
assert len(result) == 3
@pytest.mark.asyncio
async def test_escapes_braces_in_output(self, mock_config, mock_logger):
"""Test that curly braces are escaped for str.format() compatibility."""
docs_with_braces = [
MockTextDocument(
id="doc1",
text="Some {latex} content.",
title="Doc 1",
creation_date="2025-01-01",
),
]
mock_reader = AsyncMock()
mock_reader.read_files.return_value = docs_with_braces
with (
patch(
"graphrag.prompt_tune.loader.input.create_embedding",
return_value=MockEmbeddingModel(),
),
patch(
"graphrag.prompt_tune.loader.input.create_storage",
return_value=MagicMock(),
),
patch(
"graphrag.prompt_tune.loader.input.create_input_reader",
return_value=mock_reader,
),
patch(
"graphrag.prompt_tune.loader.input.create_chunker",
return_value=MockChunker(),
),
):
result = await load_docs_in_chunks(
config=mock_config,
select_method=DocSelectionType.TOP,
limit=1,
logger=mock_logger,
)
assert len(result) == 1
assert "{{latex}}" in result[0]
@pytest.mark.asyncio
async def test_limit_out_of_range_uses_default(
self, mock_config, mock_logger, sample_documents
):
"""Test that invalid limit falls back to default LIMIT."""
mock_reader = AsyncMock()
mock_reader.read_files.return_value = sample_documents
with (
patch(
"graphrag.prompt_tune.loader.input.create_embedding",
return_value=MockEmbeddingModel(),
),
patch(
"graphrag.prompt_tune.loader.input.create_storage",
return_value=MagicMock(),
),
patch(
"graphrag.prompt_tune.loader.input.create_input_reader",
return_value=mock_reader,
),
patch(
"graphrag.prompt_tune.loader.input.create_chunker",
return_value=MockChunker(),
),
patch(
"graphrag.prompt_tune.loader.input.LIMIT",
3,
),
):
result = await load_docs_in_chunks(
config=mock_config,
select_method=DocSelectionType.TOP,
limit=-1,
logger=mock_logger,
)
assert len(result) == 3
@pytest.mark.asyncio
async def test_chunks_all_documents(
self, mock_config, mock_logger, sample_documents
):
"""Test that all documents are chunked correctly."""
mock_reader = AsyncMock()
mock_reader.read_files.return_value = sample_documents
with (
patch(
"graphrag.prompt_tune.loader.input.create_embedding",
return_value=MockEmbeddingModel(),
),
patch(
"graphrag.prompt_tune.loader.input.create_storage",
return_value=MagicMock(),
),
patch(
"graphrag.prompt_tune.loader.input.create_input_reader",
return_value=mock_reader,
),
patch(
"graphrag.prompt_tune.loader.input.create_chunker",
return_value=MockChunker(),
),
):
result = await load_docs_in_chunks(
config=mock_config,
select_method=DocSelectionType.TOP,
limit=5,
logger=mock_logger,
)
assert len(result) == 5
assert "First sentence." in result
assert "Another document." in result
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/prompt_tune/test_load_docs_in_chunks.py",
"license": "MIT License",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag/graphrag/graphs/compute_degree.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Compute node degree directly from a relationships DataFrame."""
import pandas as pd
def compute_degree(
relationships: pd.DataFrame,
source_column: str = "source",
target_column: str = "target",
) -> pd.DataFrame:
"""Compute the degree of each node from an edge list DataFrame.
Degree is the number of edges connected to a node (counting both
source and target appearances).
Parameters
----------
relationships : pd.DataFrame
Edge list with at least source and target columns.
source_column : str
Name of the source node column.
target_column : str
Name of the target node column.
Returns
-------
pd.DataFrame
DataFrame with columns ["title", "degree"].
"""
# Normalize edge direction so (A,B) and (B,A) are treated as the same
# undirected edge, matching NetworkX Graph behavior.
edges = relationships[[source_column, target_column]].copy()
edges["_lo"] = edges.min(axis=1)
edges["_hi"] = edges.max(axis=1)
edges = edges.drop_duplicates(subset=["_lo", "_hi"])
source_counts = edges[source_column].value_counts()
target_counts = edges[target_column].value_counts()
degree = source_counts.add(target_counts, fill_value=0).astype(int)
return pd.DataFrame({"title": degree.index, "degree": degree.to_numpy()})
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/compute_degree.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/graphs/connected_components.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Find connected components and the largest connected component from an edge list DataFrame."""
import pandas as pd
def connected_components(
relationships: pd.DataFrame,
source_column: str = "source",
target_column: str = "target",
) -> list[set[str]]:
"""Return all connected components as a list of node-title sets.
Uses union-find on the deduplicated edge list.
Parameters
----------
relationships : pd.DataFrame
Edge list with at least source and target columns.
source_column : str
Name of the source node column.
target_column : str
Name of the target node column.
Returns
-------
list[set[str]]
Each element is a set of node titles belonging to one component,
sorted by descending component size.
"""
edges = relationships.drop_duplicates(subset=[source_column, target_column])
# Initialize every node as its own parent
all_nodes = pd.concat(
[edges[source_column], edges[target_column]], ignore_index=True
).unique()
parent: dict[str, str] = {node: node for node in all_nodes}
def find(x: str) -> str:
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression
x = parent[x]
return x
def union(a: str, b: str) -> None:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
# Union each edge
for src, tgt in zip(edges[source_column], edges[target_column], strict=True):
union(src, tgt)
# Group by root
groups: dict[str, set[str]] = {}
for node in parent:
root = find(node)
groups.setdefault(root, set()).add(node)
return sorted(groups.values(), key=len, reverse=True)
def largest_connected_component(
relationships: pd.DataFrame,
source_column: str = "source",
target_column: str = "target",
) -> set[str]:
"""Return the node titles belonging to the largest connected component.
Parameters
----------
relationships : pd.DataFrame
Edge list with at least source and target columns.
source_column : str
Name of the source node column.
target_column : str
Name of the target node column.
Returns
-------
set[str]
The set of node titles in the largest connected component.
"""
components = connected_components(
relationships,
source_column=source_column,
target_column=target_column,
)
if not components:
return set()
return components[0]
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/connected_components.py",
"license": "MIT License",
"lines": 76,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/graphs/edge_weights.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Edge weight calculation utilities (PMI, RRF)."""
import numpy as np
import pandas as pd
def calculate_pmi_edge_weights(
nodes_df: pd.DataFrame,
edges_df: pd.DataFrame,
node_name_col: str = "title",
node_freq_col: str = "frequency",
edge_weight_col: str = "weight",
edge_source_col: str = "source",
edge_target_col: str = "target",
) -> pd.DataFrame:
"""Calculate pointwise mutual information (PMI) edge weights.
Uses a variant of PMI that accounts for bias towards low-frequency events.
pmi(x,y) = p(x,y) * log2(p(x,y)/ (p(x)*p(y))
p(x,y) = edge_weight(x,y) / total_edge_weights
p(x) = freq_occurrence(x) / total_freq_occurrences.
"""
copied_nodes_df = nodes_df[[node_name_col, node_freq_col]]
total_edge_weights = edges_df[edge_weight_col].sum()
total_freq_occurrences = nodes_df[node_freq_col].sum()
copied_nodes_df["prop_occurrence"] = (
copied_nodes_df[node_freq_col] / total_freq_occurrences
)
copied_nodes_df = copied_nodes_df.loc[:, [node_name_col, "prop_occurrence"]]
edges_df["prop_weight"] = edges_df[edge_weight_col] / total_edge_weights
edges_df = (
edges_df
.merge(
copied_nodes_df,
left_on=edge_source_col,
right_on=node_name_col,
how="left",
)
.drop(columns=[node_name_col])
.rename(columns={"prop_occurrence": "source_prop"})
)
edges_df = (
edges_df
.merge(
copied_nodes_df,
left_on=edge_target_col,
right_on=node_name_col,
how="left",
)
.drop(columns=[node_name_col])
.rename(columns={"prop_occurrence": "target_prop"})
)
edges_df[edge_weight_col] = edges_df["prop_weight"] * np.log2(
edges_df["prop_weight"] / (edges_df["source_prop"] * edges_df["target_prop"])
)
return edges_df.drop(columns=["prop_weight", "source_prop", "target_prop"])
def calculate_rrf_edge_weights(
nodes_df: pd.DataFrame,
edges_df: pd.DataFrame,
node_name_col: str = "title",
node_freq_col: str = "freq",
edge_weight_col: str = "weight",
edge_source_col: str = "source",
edge_target_col: str = "target",
rrf_smoothing_factor: int = 60,
) -> pd.DataFrame:
"""Calculate reciprocal rank fusion (RRF) edge weights.
Combines PMI weight and combined freq of source and target.
"""
edges_df = calculate_pmi_edge_weights(
nodes_df,
edges_df,
node_name_col,
node_freq_col,
edge_weight_col,
edge_source_col,
edge_target_col,
)
edges_df["pmi_rank"] = edges_df[edge_weight_col].rank(method="min", ascending=False)
edges_df["raw_weight_rank"] = edges_df[edge_weight_col].rank(
method="min", ascending=False
)
edges_df[edge_weight_col] = edges_df.apply(
lambda x: (
(1 / (rrf_smoothing_factor + x["pmi_rank"]))
+ (1 / (rrf_smoothing_factor + x["raw_weight_rank"]))
),
axis=1,
)
return edges_df.drop(columns=["pmi_rank", "raw_weight_rank"])
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/edge_weights.py",
"license": "MIT License",
"lines": 88,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/graphs/hierarchical_leiden.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Hierarchical Leiden clustering on edge lists."""
from typing import Any
import graspologic_native as gn
def hierarchical_leiden(
edges: list[tuple[str, str, float]],
max_cluster_size: int = 10,
random_seed: int | None = 0xDEADBEEF,
) -> list[gn.HierarchicalCluster]:
"""Run hierarchical leiden on an edge list."""
return gn.hierarchical_leiden(
edges=edges,
max_cluster_size=max_cluster_size,
seed=random_seed,
starting_communities=None,
resolution=1.0,
randomness=0.001,
use_modularity=True,
iterations=1,
)
def first_level_hierarchical_clustering(
hcs: list[gn.HierarchicalCluster],
) -> dict[Any, int]:
"""Return the initial leiden clustering as a dict of node id to community id.
Returns
-------
dict[Any, int]
The initial leiden algorithm clustering results as a dictionary
of node id to community id.
"""
return {entry.node: entry.cluster for entry in hcs if entry.level == 0}
def final_level_hierarchical_clustering(
hcs: list[gn.HierarchicalCluster],
) -> dict[Any, int]:
"""Return the final leiden clustering as a dict of node id to community id.
Returns
-------
dict[Any, int]
The last leiden algorithm clustering results as a dictionary
of node id to community id.
"""
return {entry.node: entry.cluster for entry in hcs if entry.is_final_cluster}
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/hierarchical_leiden.py",
"license": "MIT License",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/graphs/modularity.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Compute graph modularity directly from an edge list DataFrame."""
import logging
import math
from collections import defaultdict
import pandas as pd
from graphrag.config.enums import ModularityMetric
from graphrag.graphs.connected_components import (
connected_components,
largest_connected_component,
)
from graphrag.graphs.hierarchical_leiden import (
final_level_hierarchical_clustering,
first_level_hierarchical_clustering,
hierarchical_leiden,
)
logger = logging.getLogger(__name__)
def _df_to_edge_list(
edges: pd.DataFrame,
source_column: str = "source",
target_column: str = "target",
weight_column: str = "weight",
) -> list[tuple[str, str, float]]:
"""Convert a relationships DataFrame to a sorted edge list.
Normalizes direction and deduplicates so each undirected edge appears
once, keeping the last occurrence's weight (matching NX behavior).
"""
df = edges[[source_column, target_column, weight_column]].copy()
lo = df[[source_column, target_column]].min(axis=1)
hi = df[[source_column, target_column]].max(axis=1)
df = df.assign(**{source_column: lo, target_column: hi})
df = df.drop_duplicates(subset=[source_column, target_column], keep="last")
return sorted(
(str(row[source_column]), str(row[target_column]), float(row[weight_column]))
for _, row in df.iterrows()
)
def modularity(
edges: pd.DataFrame,
partitions: dict[str, int],
source_column: str = "source",
target_column: str = "target",
weight_column: str = "weight",
resolution: float = 1.0,
) -> float:
"""Calculate modularity of a graph given community assignments.
Parameters
----------
edges : pd.DataFrame
Edge list with at least source, target, and weight columns.
partitions : dict[str, int]
Mapping from node title to community id.
source_column : str
Name of the source node column.
target_column : str
Name of the target node column.
weight_column : str
Name of the edge weight column.
resolution : float
Resolution parameter for modularity calculation.
Returns
-------
float
The modularity score.
"""
components = _modularity_components(
edges, partitions, source_column, target_column, weight_column, resolution
)
return sum(components.values())
def _modularity_component(
intra_community_degree: float,
total_community_degree: float,
network_degree_sum: float,
resolution: float,
) -> float:
"""Compute the modularity contribution of a single community."""
community_degree_ratio = math.pow(total_community_degree, 2.0) / (
2.0 * network_degree_sum
)
return (intra_community_degree - resolution * community_degree_ratio) / (
2.0 * network_degree_sum
)
def _modularity_components(
edges: pd.DataFrame,
partitions: dict[str, int],
source_column: str = "source",
target_column: str = "target",
weight_column: str = "weight",
resolution: float = 1.0,
) -> dict[int, float]:
"""Calculate per-community modularity components from an edge list.
Edges are treated as undirected: direction is normalized and duplicates
are removed (keeping the last occurrence's weight, matching NX behavior).
"""
# Normalize direction and deduplicate so each undirected edge is counted once
df = edges[[source_column, target_column, weight_column]].copy()
lo = df[[source_column, target_column]].min(axis=1)
hi = df[[source_column, target_column]].max(axis=1)
df = df.assign(**{source_column: lo, target_column: hi})
df = df.drop_duplicates(subset=[source_column, target_column], keep="last")
total_edge_weight = 0.0
communities = set(partitions.values())
degree_sums_within: dict[int, float] = defaultdict(float)
degree_sums_for: dict[int, float] = defaultdict(float)
for _, row in df.iterrows():
src = str(row[source_column])
tgt = str(row[target_column])
weight = float(row[weight_column])
src_comm = partitions[src]
tgt_comm = partitions[tgt]
if src_comm == tgt_comm:
if src == tgt:
degree_sums_within[src_comm] += weight
else:
degree_sums_within[src_comm] += weight * 2.0
degree_sums_for[src_comm] += weight
degree_sums_for[tgt_comm] += weight
total_edge_weight += weight
if total_edge_weight == 0.0:
return dict.fromkeys(communities, 0.0)
return {
comm: _modularity_component(
degree_sums_within[comm],
degree_sums_for[comm],
total_edge_weight,
resolution,
)
for comm in communities
}
def calculate_root_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
) -> float:
"""Calculate modularity of the graph's root clusters."""
edge_list = _df_to_edge_list(edges)
hcs = hierarchical_leiden(
edge_list,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
)
root_clusters = first_level_hierarchical_clustering(hcs)
return modularity(edges, root_clusters)
def calculate_leaf_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
) -> float:
"""Calculate modularity of the graph's leaf clusters."""
edge_list = _df_to_edge_list(edges)
hcs = hierarchical_leiden(
edge_list,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
)
leaf_clusters = final_level_hierarchical_clustering(hcs)
return modularity(edges, leaf_clusters)
def calculate_graph_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
use_root_modularity: bool = True,
) -> float:
"""Calculate modularity of the whole graph."""
if use_root_modularity:
return calculate_root_modularity(
edges, max_cluster_size=max_cluster_size, random_seed=random_seed
)
return calculate_leaf_modularity(
edges, max_cluster_size=max_cluster_size, random_seed=random_seed
)
def calculate_lcc_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
use_root_modularity: bool = True,
) -> float:
"""Calculate modularity of the largest connected component of the graph."""
lcc_nodes = largest_connected_component(edges)
lcc_edges = edges[edges["source"].isin(lcc_nodes) & edges["target"].isin(lcc_nodes)]
if use_root_modularity:
return calculate_root_modularity(
lcc_edges, max_cluster_size=max_cluster_size, random_seed=random_seed
)
return calculate_leaf_modularity(
lcc_edges, max_cluster_size=max_cluster_size, random_seed=random_seed
)
def calculate_weighted_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
min_connected_component_size: int = 10,
use_root_modularity: bool = True,
) -> float:
"""Calculate weighted modularity of components larger than *min_connected_component_size*.
Modularity = sum(component_modularity * component_size) / total_nodes.
"""
components = connected_components(edges)
filtered = [c for c in components if len(c) > min_connected_component_size]
if len(filtered) == 0:
# Fall back to the whole graph
filtered = [set(edges["source"].unique()).union(set(edges["target"].unique()))]
total_nodes = sum(len(c) for c in filtered)
total_modularity = 0.0
for component in filtered:
if len(component) > min_connected_component_size:
sub_edges = edges[
edges["source"].isin(component) & edges["target"].isin(component)
]
if use_root_modularity:
mod = calculate_root_modularity(
sub_edges,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
)
else:
mod = calculate_leaf_modularity(
sub_edges,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
)
total_modularity += mod * len(component) / total_nodes
return total_modularity
def calculate_modularity(
edges: pd.DataFrame,
max_cluster_size: int = 10,
random_seed: int = 0xDEADBEEF,
use_root_modularity: bool = True,
modularity_metric: ModularityMetric = ModularityMetric.WeightedComponents,
) -> float:
"""Calculate modularity of the graph based on the modularity metric type."""
match modularity_metric:
case ModularityMetric.Graph:
logger.info("Calculating graph modularity")
return calculate_graph_modularity(
edges,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
use_root_modularity=use_root_modularity,
)
case ModularityMetric.LCC:
logger.info("Calculating LCC modularity")
return calculate_lcc_modularity(
edges,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
use_root_modularity=use_root_modularity,
)
case ModularityMetric.WeightedComponents:
logger.info("Calculating weighted-components modularity")
return calculate_weighted_modularity(
edges,
max_cluster_size=max_cluster_size,
random_seed=random_seed,
use_root_modularity=use_root_modularity,
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/modularity.py",
"license": "MIT License",
"lines": 256,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/graphs/stable_lcc.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Produce a stable largest connected component from a relationships DataFrame.
"Stable" means the same input edge list always produces the same output,
regardless of the original row order. This is achieved by:
1. Filtering to the largest connected component.
2. Normalizing node names (HTML unescape, uppercase, strip).
3. Sorting edges so the lesser node is always the source.
4. Sorting edges alphabetically for deterministic row order.
"""
import html
import pandas as pd
from graphrag.graphs.connected_components import largest_connected_component
def stable_lcc(
relationships: pd.DataFrame,
source_column: str = "source",
target_column: str = "target",
) -> pd.DataFrame:
"""Return the relationships DataFrame filtered to a stable largest connected component.
Parameters
----------
relationships : pd.DataFrame
Edge list with at least source and target columns.
source_column : str
Name of the source node column.
target_column : str
Name of the target node column.
Returns
-------
pd.DataFrame
A copy of the input filtered to the LCC with normalized node names
and deterministic edge ordering.
"""
if relationships.empty:
return relationships.copy()
# 1. Normalize node names
edges = relationships.copy()
edges[source_column] = edges[source_column].apply(_normalize_name)
edges[target_column] = edges[target_column].apply(_normalize_name)
# 2. Filter to the largest connected component
lcc_nodes = largest_connected_component(
edges, source_column=source_column, target_column=target_column
)
edges = edges[
edges[source_column].isin(lcc_nodes) & edges[target_column].isin(lcc_nodes)
]
# 3. Stabilize edge direction: lesser node always first
swapped = edges[source_column] > edges[target_column]
edges.loc[swapped, [source_column, target_column]] = edges.loc[
swapped, [target_column, source_column]
].to_numpy()
# 4. Deduplicate edges that were reversed pairs in the original data
edges = edges.drop_duplicates(subset=[source_column, target_column])
# 5. Sort for deterministic order
return edges.sort_values([source_column, target_column]).reset_index(drop=True)
def _normalize_name(name: str) -> str:
"""Normalize a node name: HTML unescape, uppercase, strip whitespace."""
return html.unescape(name).upper().strip()
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/graphs/stable_lcc.py",
"license": "MIT License",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/graphs/test_compute_degree.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Side-by-side tests comparing NetworkX compute_degree with DataFrame-based compute_degree_df."""
import json
from pathlib import Path
import networkx as nx
import pandas as pd
from graphrag.graphs.compute_degree import compute_degree as compute_degree_df
from pandas.testing import assert_frame_equal
FIXTURES_DIR = Path(__file__).parent / "fixtures"
def _make_relationships(*edges: tuple[str, str, float]) -> pd.DataFrame:
"""Build a relationships DataFrame from (source, target, weight) tuples."""
return pd.DataFrame([{"source": s, "target": t, "weight": w} for s, t, w in edges])
def _normalize(df: pd.DataFrame) -> pd.DataFrame:
"""Sort by title and reset index for comparison."""
return df.sort_values("title").reset_index(drop=True)
def _compute_degree_via_nx(relationships: pd.DataFrame) -> pd.DataFrame:
"""Compute degree using NetworkX directly."""
graph = nx.from_pandas_edgelist(
relationships, source="source", target="target", edge_attr=["weight"]
)
return pd.DataFrame([
{"title": node, "degree": int(degree)} for node, degree in graph.degree
])
def test_simple_triangle():
"""Three nodes forming a triangle — each should have degree 2."""
rels = _make_relationships(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_star_topology():
"""One hub connected to many leaves."""
rels = _make_relationships(
("hub", "a", 1.0),
("hub", "b", 1.0),
("hub", "c", 1.0),
("hub", "d", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
# hub should have degree 4
hub_row = df_result[df_result["title"] == "hub"]
assert hub_row["degree"].iloc[0] == 4
def test_disconnected_components():
"""Two separate components."""
rels = _make_relationships(
("A", "B", 1.0),
("C", "D", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_single_edge():
"""Simplest case: one edge, two nodes, each with degree 1."""
rels = _make_relationships(("X", "Y", 1.0))
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_self_loop():
"""A self-loop contributes degree 2 in NetworkX for undirected graphs."""
rels = _make_relationships(
("A", "A", 1.0),
("A", "B", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_duplicate_edges():
"""Duplicate edges in the DataFrame — NetworkX deduplicates, so should we check behavior."""
rels = _make_relationships(
("A", "B", 1.0),
("A", "B", 2.0),
("B", "C", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_larger_graph():
"""A larger graph to exercise multiple degree values."""
rels = _make_relationships(
("A", "B", 1.0),
("A", "C", 1.0),
("A", "D", 1.0),
("B", "C", 1.0),
("D", "E", 1.0),
("E", "F", 1.0),
)
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
def test_fixture_graph():
"""Degree computation on the realistic A Christmas Carol fixture should match NetworkX."""
with open(FIXTURES_DIR / "graph.json") as f:
data = json.load(f)
rels = pd.DataFrame(data["edges"])
nx_result = _normalize(_compute_degree_via_nx(rels))
df_result = _normalize(compute_degree_df(rels))
assert_frame_equal(nx_result, df_result)
assert len(df_result) > 500 # sanity: realistic graph has 500+ nodes
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/graphs/test_compute_degree.py",
"license": "MIT License",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/graphs/test_connected_components.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Side-by-side tests comparing NetworkX connected components with DataFrame-based implementation."""
import json
from pathlib import Path
import networkx as nx
import pandas as pd
from graphrag.graphs.connected_components import (
connected_components,
largest_connected_component,
)
FIXTURES_DIR = Path(__file__).parent / "fixtures"
def _load_fixture() -> pd.DataFrame:
"""Load the realistic graph fixture as a relationships DataFrame."""
with open(FIXTURES_DIR / "graph.json") as f:
data = json.load(f)
return pd.DataFrame(data["edges"])
def _make_relationships(*edges: tuple[str, str, float]) -> pd.DataFrame:
"""Build a relationships DataFrame from (source, target, weight) tuples."""
return pd.DataFrame([{"source": s, "target": t, "weight": w} for s, t, w in edges])
# ---------------------------------------------------------------------------
# NetworkX reference helpers
# ---------------------------------------------------------------------------
def _nx_connected_components(relationships: pd.DataFrame) -> list[set[str]]:
"""Compute connected components using NetworkX."""
graph = nx.from_pandas_edgelist(relationships, source="source", target="target")
return sorted(
[set(c) for c in nx.connected_components(graph)],
key=len,
reverse=True,
)
def _nx_largest_connected_component(relationships: pd.DataFrame) -> set[str]:
"""Return the LCC using NetworkX."""
components = _nx_connected_components(relationships)
return components[0] if components else set()
# ---------------------------------------------------------------------------
# Simple topology tests
# ---------------------------------------------------------------------------
def test_single_component():
"""Fully connected graph should have one component."""
rels = _make_relationships(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
)
nx_components = _nx_connected_components(rels)
df_components = connected_components(rels)
assert len(nx_components) == len(df_components) == 1
assert nx_components[0] == df_components[0]
def test_two_components():
"""Two disconnected pairs should give two components."""
rels = _make_relationships(
("A", "B", 1.0),
("C", "D", 1.0),
)
nx_components = _nx_connected_components(rels)
df_components = connected_components(rels)
assert len(nx_components) == len(df_components) == 2
assert {frozenset(c) for c in nx_components} == {
frozenset(c) for c in df_components
}
def test_three_components_lcc():
"""LCC should pick the largest of three components."""
rels = _make_relationships(
("A", "B", 1.0),
("A", "C", 1.0),
("A", "D", 1.0),
("X", "Y", 1.0),
("P", "Q", 1.0),
)
nx_lcc = _nx_largest_connected_component(rels)
df_lcc = largest_connected_component(rels)
assert nx_lcc == df_lcc
assert df_lcc == {"A", "B", "C", "D"}
def test_star_topology():
"""Star should be a single component."""
rels = _make_relationships(
("hub", "a", 1.0),
("hub", "b", 1.0),
("hub", "c", 1.0),
)
df_lcc = largest_connected_component(rels)
nx_lcc = _nx_largest_connected_component(rels)
assert df_lcc == nx_lcc == {"hub", "a", "b", "c"}
def test_duplicate_edges():
"""Duplicate edges should not affect component membership."""
rels = _make_relationships(
("A", "B", 1.0),
("A", "B", 2.0),
("C", "D", 1.0),
)
nx_components = _nx_connected_components(rels)
df_components = connected_components(rels)
assert len(nx_components) == len(df_components) == 2
assert {frozenset(c) for c in nx_components} == {
frozenset(c) for c in df_components
}
def test_empty_relationships():
"""Empty edge list should produce no components."""
rels = pd.DataFrame(columns=["source", "target", "weight"])
assert connected_components(rels) == []
assert largest_connected_component(rels) == set()
# ---------------------------------------------------------------------------
# Realistic fixture tests
# ---------------------------------------------------------------------------
def test_fixture_component_count():
"""Component count should match NetworkX on the realistic fixture."""
rels = _load_fixture()
nx_components = _nx_connected_components(rels)
df_components = connected_components(rels)
assert len(df_components) == len(nx_components)
def test_fixture_component_sizes():
"""Component sizes (sorted desc) should match NetworkX."""
rels = _load_fixture()
nx_sizes = [len(c) for c in _nx_connected_components(rels)]
df_sizes = [len(c) for c in connected_components(rels)]
assert df_sizes == nx_sizes
def test_fixture_lcc_membership():
"""LCC membership should be identical to NetworkX."""
rels = _load_fixture()
nx_lcc = _nx_largest_connected_component(rels)
df_lcc = largest_connected_component(rels)
assert df_lcc == nx_lcc
def test_fixture_lcc_size():
"""LCC should contain 535 nodes (known from the fixture)."""
rels = _load_fixture()
lcc = largest_connected_component(rels)
assert len(lcc) == 535
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/graphs/test_connected_components.py",
"license": "MIT License",
"lines": 128,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/graphs/test_modularity.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Side-by-side tests for the DataFrame-based modularity utility."""
import json
import math
from collections import defaultdict
from pathlib import Path
from typing import Any
import networkx as nx
import pandas as pd
from graphrag.graphs.modularity import modularity
FIXTURES_DIR = Path(__file__).parent / "fixtures"
# ---------------------------------------------------------------------------
# NX reference implementation (copied from graphrag.index.utils.graphs)
# ---------------------------------------------------------------------------
def _nx_modularity_component(
intra_community_degree: float,
total_community_degree: float,
network_degree_sum: float,
resolution: float,
) -> float:
community_degree_ratio = math.pow(total_community_degree, 2.0) / (
2.0 * network_degree_sum
)
return (intra_community_degree - resolution * community_degree_ratio) / (
2.0 * network_degree_sum
)
def _nx_modularity_components(
graph: nx.Graph,
partitions: dict[Any, int],
weight_attribute: str = "weight",
resolution: float = 1.0,
) -> dict[int, float]:
total_edge_weight = 0.0
communities = set(partitions.values())
degree_sums_within_community: dict[int, float] = defaultdict(float)
degree_sums_for_community: dict[int, float] = defaultdict(float)
for vertex, neighbor_vertex, weight in graph.edges(data=weight_attribute):
vertex_community = partitions[vertex]
neighbor_community = partitions[neighbor_vertex]
if vertex_community == neighbor_community:
if vertex == neighbor_vertex:
degree_sums_within_community[vertex_community] += weight
else:
degree_sums_within_community[vertex_community] += weight * 2.0
degree_sums_for_community[vertex_community] += weight
degree_sums_for_community[neighbor_community] += weight
total_edge_weight += weight
return {
comm: _nx_modularity_component(
degree_sums_within_community[comm],
degree_sums_for_community[comm],
total_edge_weight,
resolution,
)
for comm in communities
}
def nx_modularity(
graph: nx.Graph,
partitions: dict[Any, int],
weight_attribute: str = "weight",
resolution: float = 1.0,
) -> float:
"""NX reference: compute modularity from a networkx graph."""
components = _nx_modularity_components(
graph, partitions, weight_attribute, resolution
)
return sum(components.values())
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load_fixture() -> pd.DataFrame:
"""Load the realistic graph fixture as a relationships DataFrame."""
with open(FIXTURES_DIR / "graph.json") as f:
data = json.load(f)
return pd.DataFrame(data["edges"])
def _make_edges(*edges: tuple[str, str, float]) -> pd.DataFrame:
"""Build a relationships DataFrame from (source, target, weight) tuples."""
return pd.DataFrame([{"source": s, "target": t, "weight": w} for s, t, w in edges])
def _edges_to_nx(edges: pd.DataFrame) -> nx.Graph:
"""Build an NX graph from an edges DataFrame."""
return nx.from_pandas_edgelist(edges, edge_attr=["weight"])
# ---------------------------------------------------------------------------
# Side-by-side tests
# ---------------------------------------------------------------------------
def test_two_clear_communities():
"""Two densely-connected communities with a weak bridge."""
edges = _make_edges(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
("D", "E", 1.0),
("E", "F", 1.0),
("D", "F", 1.0),
("C", "D", 0.1),
)
partitions = {"A": 0, "B": 0, "C": 0, "D": 1, "E": 1, "F": 1}
nx_result = nx_modularity(_edges_to_nx(edges), partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10
assert df_result > 0 # good partition should be positive
def test_single_community():
"""All nodes in one community — modularity should be zero."""
edges = _make_edges(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
)
partitions = {"A": 0, "B": 0, "C": 0}
nx_result = nx_modularity(_edges_to_nx(edges), partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10
assert abs(df_result) < 1e-10
def test_every_node_own_community():
"""Each node in its own community — modularity should be negative."""
edges = _make_edges(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
)
partitions = {"A": 0, "B": 1, "C": 2}
nx_result = nx_modularity(_edges_to_nx(edges), partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10
assert df_result < 0
def test_reversed_edges():
"""Reversed edge direction should not affect modularity (undirected)."""
edges_fwd = _make_edges(("A", "B", 1.0), ("B", "C", 1.0), ("C", "D", 1.0))
edges_rev = _make_edges(("B", "A", 1.0), ("C", "B", 1.0), ("D", "C", 1.0))
partitions = {"A": 0, "B": 0, "C": 1, "D": 1}
fwd = modularity(edges_fwd, partitions)
rev = modularity(edges_rev, partitions)
assert abs(fwd - rev) < 1e-10
def test_weighted_edges():
"""Different weights should affect modularity."""
edges_uniform = _make_edges(
("A", "B", 1.0),
("B", "C", 1.0),
("C", "D", 1.0),
)
edges_weighted = _make_edges(
("A", "B", 5.0),
("B", "C", 0.1),
("C", "D", 5.0),
)
partitions = {"A": 0, "B": 0, "C": 1, "D": 1}
u_nx = nx_modularity(_edges_to_nx(edges_uniform), partitions)
u_df = modularity(edges_uniform, partitions)
w_nx = nx_modularity(_edges_to_nx(edges_weighted), partitions)
w_df = modularity(edges_weighted, partitions)
assert abs(u_nx - u_df) < 1e-10
assert abs(w_nx - w_df) < 1e-10
# weighted version should have higher modularity (strong intra, weak inter)
assert w_df > u_df
def test_custom_resolution():
"""Resolution parameter should affect result and match NX."""
edges = _make_edges(
("A", "B", 1.0),
("B", "C", 1.0),
("A", "C", 1.0),
("D", "E", 1.0),
("C", "D", 0.5),
)
partitions = {"A": 0, "B": 0, "C": 0, "D": 1, "E": 1}
graph = _edges_to_nx(edges)
for res in (0.5, 1.0, 2.0):
nx_r = nx_modularity(graph, partitions, resolution=res)
df_r = modularity(edges, partitions, resolution=res)
assert abs(nx_r - df_r) < 1e-10
def test_duplicate_edges():
"""Duplicate edges (same pair, different weights) should match NX dedup."""
edges = _make_edges(
("A", "B", 1.0),
("A", "B", 3.0), # duplicate — NX keeps last
("B", "C", 2.0),
)
partitions = {"A": 0, "B": 0, "C": 1}
nx_result = nx_modularity(_edges_to_nx(edges), partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10
def test_reversed_duplicate_edges():
"""Edge (A,B) and (B,A) should be treated as the same, keeping last weight."""
edges = _make_edges(
("A", "B", 1.0),
("B", "A", 5.0), # reversed duplicate — NX keeps 5.0
("B", "C", 2.0),
)
partitions = {"A": 0, "B": 0, "C": 1}
nx_result = nx_modularity(_edges_to_nx(edges), partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10
def test_fixture_matches_nx():
"""Modularity on the fixture graph should match NX for several partitions."""
edges = _load_fixture()
graph = _edges_to_nx(edges)
nodes = sorted(graph.nodes())
# Test with a few different partition schemes
for n_communities in (2, 3, 5):
partitions = {node: i % n_communities for i, node in enumerate(nodes)}
nx_result = nx_modularity(graph, partitions)
df_result = modularity(edges, partitions)
assert abs(nx_result - df_result) < 1e-10, (
f"Mismatch for {n_communities} communities: NX={nx_result}, DF={df_result}"
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/graphs/test_modularity.py",
"license": "MIT License",
"lines": 204,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:tests/unit/graphs/test_stable_lcc.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Side-by-side tests for the DataFrame-based stable LCC utility."""
import json
from pathlib import Path
import networkx as nx
import pandas as pd
from graphrag.graphs.stable_lcc import stable_lcc
from pandas.testing import assert_frame_equal
from tests.unit.graphs.nx_stable_lcc import stable_largest_connected_component
FIXTURES_DIR = Path(__file__).parent / "fixtures"
def _load_fixture() -> pd.DataFrame:
"""Load the realistic graph fixture as a relationships DataFrame."""
with open(FIXTURES_DIR / "graph.json") as f:
data = json.load(f)
return pd.DataFrame(data["edges"])
def _make_relationships(*edges: tuple[str, str, float]) -> pd.DataFrame:
"""Build a relationships DataFrame from (source, target, weight) tuples."""
return pd.DataFrame([{"source": s, "target": t, "weight": w} for s, t, w in edges])
def _nx_stable_lcc_node_set(relationships: pd.DataFrame) -> set[str]:
"""Get the node set from the NX stable_largest_connected_component."""
graph = nx.from_pandas_edgelist(
relationships,
source="source",
target="target",
edge_attr=["weight"],
)
stable_graph = stable_largest_connected_component(graph)
return set(stable_graph.nodes())
def _nx_stable_lcc_edge_set(relationships: pd.DataFrame) -> set[tuple[str, str]]:
"""Get the edge set from the NX stable_largest_connected_component."""
graph = nx.from_pandas_edgelist(
relationships,
source="source",
target="target",
edge_attr=["weight"],
)
stable_graph = stable_largest_connected_component(graph)
return {(min(s, t), max(s, t)) for s, t in stable_graph.edges()}
# ---------------------------------------------------------------------------
# Stability tests
# ---------------------------------------------------------------------------
def test_flipped_edges_produce_same_result():
"""Same graph with edges in different direction should produce identical output."""
rels_1 = _make_relationships(
("A", "B", 1.0),
("B", "C", 2.0),
("C", "D", 3.0),
("D", "E", 4.0),
)
rels_2 = _make_relationships(
("B", "A", 1.0),
("C", "B", 2.0),
("D", "C", 3.0),
("E", "D", 4.0),
)
result_1 = stable_lcc(rels_1)
result_2 = stable_lcc(rels_2)
assert_frame_equal(result_1, result_2)
def test_shuffled_rows_produce_same_result():
"""Different row order should produce identical output."""
rels_1 = _make_relationships(
("A", "B", 1.0),
("B", "C", 2.0),
("C", "D", 3.0),
)
rels_2 = _make_relationships(
("C", "D", 3.0),
("A", "B", 1.0),
("B", "C", 2.0),
)
result_1 = stable_lcc(rels_1)
result_2 = stable_lcc(rels_2)
assert_frame_equal(result_1, result_2)
# ---------------------------------------------------------------------------
# Name normalization tests
# ---------------------------------------------------------------------------
def test_normalizes_node_names():
"""Node names should be uppercased, stripped, and HTML-unescaped."""
rels = _make_relationships(
(" alice ", "bob", 1.0),
("bob", "carol & dave", 1.0),
)
result = stable_lcc(rels)
all_nodes = set(result["source"]).union(result["target"])
assert "ALICE" in all_nodes
assert "BOB" in all_nodes
assert "CAROL & DAVE" in all_nodes
# ---------------------------------------------------------------------------
# LCC filtering tests
# ---------------------------------------------------------------------------
def test_filters_to_lcc():
"""Only the largest component should remain."""
rels = _make_relationships(
("A", "B", 1.0),
("B", "C", 1.0),
("C", "A", 1.0),
("X", "Y", 1.0),
)
result = stable_lcc(rels)
all_nodes = set(result["source"]).union(result["target"])
assert all_nodes == {"A", "B", "C"}
def test_empty_relationships():
"""Empty input should return empty output."""
rels = pd.DataFrame(columns=["source", "target", "weight"])
result = stable_lcc(rels)
assert result.empty
# ---------------------------------------------------------------------------
# Side-by-side with NX implementation
# ---------------------------------------------------------------------------
def test_node_set_matches_nx():
"""LCC node set should match the NX stable_largest_connected_component."""
rels = _make_relationships(
("A", "B", 1.0),
("B", "C", 1.0),
("C", "D", 1.0),
("D", "E", 1.0),
("X", "Y", 1.0),
)
nx_nodes = _nx_stable_lcc_node_set(rels)
df_result = stable_lcc(rels)
df_nodes = set(df_result["source"]).union(df_result["target"])
assert df_nodes == nx_nodes
def test_edge_set_matches_nx():
"""LCC edge set should match the NX stable_largest_connected_component."""
rels = _make_relationships(
("A", "B", 1.0),
("B", "C", 1.0),
("C", "D", 1.0),
("D", "E", 1.0),
("X", "Y", 1.0),
)
nx_edges = _nx_stable_lcc_edge_set(rels)
df_result = stable_lcc(rels)
df_edges = {
(min(s, t), max(s, t))
for s, t in zip(df_result["source"], df_result["target"], strict=True)
}
assert df_edges == nx_edges
# ---------------------------------------------------------------------------
# Fixture tests
# ---------------------------------------------------------------------------
def test_fixture_node_set_matches_nx():
"""Fixture LCC nodes should match NX stable LCC."""
rels = _load_fixture()
nx_nodes = _nx_stable_lcc_node_set(rels)
df_result = stable_lcc(rels)
df_nodes = set(df_result["source"]).union(df_result["target"])
assert df_nodes == nx_nodes
def test_fixture_edge_set_matches_nx():
"""Fixture LCC edges should match NX stable LCC."""
rels = _load_fixture()
nx_edges = _nx_stable_lcc_edge_set(rels)
df_result = stable_lcc(rels)
df_edges = {
(min(s, t), max(s, t))
for s, t in zip(df_result["source"], df_result["target"], strict=True)
}
assert df_edges == nx_edges
def test_fixture_edges_are_sorted():
"""Output edges should be sorted with source <= target and rows in order."""
rels = _load_fixture()
result = stable_lcc(rels)
# Every source should be <= target
assert (result["source"] <= result["target"]).all()
# Rows should be sorted
is_sorted = (
result[["source", "target"]].apply(tuple, axis=1).is_monotonic_increasing
)
assert is_sorted
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/graphs/test_stable_lcc.py",
"license": "MIT License",
"lines": 170,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag/graphrag/index/run/profiling.py | # Copyright (C) 2025 Microsoft
# Licensed under the MIT License
"""Workflow profiling utilities."""
import time
import tracemalloc
from types import TracebackType
from typing import Self
from graphrag.index.typing.stats import WorkflowMetrics
class WorkflowProfiler:
"""Context manager for profiling workflow execution.
Captures timing and memory metrics using tracemalloc. Designed to wrap
workflow execution in run_pipeline with minimal code intrusion.
Example
-------
with WorkflowProfiler() as profiler:
result = await workflow_function(config, context)
metrics = profiler.metrics
"""
def __init__(self) -> None:
self._start_time: float = 0.0
self._elapsed: float = 0.0
self._peak_memory: int = 0
self._current_memory: int = 0
self._tracemalloc_overhead: int = 0
def __enter__(self) -> Self:
"""Start profiling: begin tracemalloc and record start time."""
tracemalloc.start()
self._start_time = time.time()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Stop profiling: capture metrics and stop tracemalloc."""
self._elapsed = time.time() - self._start_time
self._current_memory, self._peak_memory = tracemalloc.get_traced_memory()
self._tracemalloc_overhead = tracemalloc.get_tracemalloc_memory()
tracemalloc.stop()
@property
def metrics(self) -> WorkflowMetrics:
"""Return collected metrics as a WorkflowMetrics dataclass."""
return WorkflowMetrics(
overall=self._elapsed,
peak_memory_bytes=self._peak_memory,
memory_delta_bytes=self._current_memory,
tracemalloc_overhead_bytes=self._tracemalloc_overhead,
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/index/run/profiling.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/indexing/test_profiling.py | # Copyright (C) 2025 Microsoft
# Licensed under the MIT License
"""Unit tests for WorkflowProfiler."""
import time
from graphrag.index.run.profiling import WorkflowProfiler
from graphrag.index.typing.stats import WorkflowMetrics
class TestWorkflowProfiler:
"""Tests for the WorkflowProfiler context manager."""
def test_captures_time(self):
"""Verify profiler captures elapsed time."""
with WorkflowProfiler() as profiler:
time.sleep(0.05) # Sleep 50ms
metrics = profiler.metrics
assert metrics.overall >= 0.05
assert metrics.overall < 0.5 # Should not take too long
def test_captures_peak_memory(self):
"""Verify profiler captures peak memory from allocations."""
with WorkflowProfiler() as profiler:
# Allocate ~1MB of data
data = [0] * (1024 * 1024 // 8) # 1M integers ≈ 8MB on 64-bit
_ = data # Keep reference to prevent GC
metrics = profiler.metrics
assert metrics.peak_memory_bytes > 0
def test_captures_memory_delta(self):
"""Verify profiler captures memory delta (current allocation)."""
with WorkflowProfiler() as profiler:
_data = [0] * 10000 # Keep allocation in scope
metrics = profiler.metrics
# Memory delta should be non-negative
assert metrics.memory_delta_bytes >= 0
def test_captures_tracemalloc_overhead(self):
"""Verify profiler captures tracemalloc's own memory overhead."""
with WorkflowProfiler() as profiler:
_ = list(range(1000))
metrics = profiler.metrics
assert metrics.tracemalloc_overhead_bytes > 0
def test_returns_workflow_metrics_dataclass(self):
"""Verify profiler.metrics returns a WorkflowMetrics instance."""
with WorkflowProfiler() as profiler:
pass
metrics = profiler.metrics
assert isinstance(metrics, WorkflowMetrics)
def test_all_metrics_populated(self):
"""Verify all four metrics are populated after profiling."""
with WorkflowProfiler() as profiler:
_ = list(range(100))
metrics = profiler.metrics
assert metrics.overall >= 0
assert metrics.peak_memory_bytes >= 0
assert metrics.memory_delta_bytes >= 0
assert metrics.tracemalloc_overhead_bytes >= 0
def test_handles_exception_in_context(self):
"""Verify profiler captures metrics even when exception is raised."""
profiler: WorkflowProfiler | None = None
try:
with WorkflowProfiler() as profiler:
_ = [0] * 1000
msg = "Test exception"
raise ValueError(msg)
except ValueError:
pass
assert profiler is not None
metrics = profiler.metrics
assert metrics.overall > 0
assert metrics.peak_memory_bytes > 0
def test_multiple_profilers_independent(self):
"""Verify multiple profiler instances don't interfere."""
with WorkflowProfiler() as profiler1:
time.sleep(0.02)
with WorkflowProfiler() as profiler2:
time.sleep(0.04)
# profiler2 should have longer time
assert profiler2.metrics.overall > profiler1.metrics.overall
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/indexing/test_profiling.py",
"license": "MIT License",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag/graphrag/data_model/data_reader.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""A DataReader that loads typed dataframes from a TableProvider."""
import pandas as pd
from graphrag_storage.tables import TableProvider
from graphrag.data_model.dfs import (
communities_typed,
community_reports_typed,
covariates_typed,
documents_typed,
entities_typed,
relationships_typed,
text_units_typed,
)
class DataReader:
"""Reads dataframes from a TableProvider and applies correct column types.
When loading from weakly-typed formats like CSV, list columns are stored as
plain strings. This class wraps a TableProvider, loading each table and
converting columns to their expected types before returning.
"""
def __init__(self, table_provider: TableProvider) -> None:
"""Initialize a DataReader with the given TableProvider.
Args
----
table_provider: TableProvider
The table provider to load dataframes from.
"""
self._table_provider = table_provider
async def entities(self) -> pd.DataFrame:
"""Load and return the entities dataframe with correct types."""
df = await self._table_provider.read_dataframe("entities")
return entities_typed(df)
async def relationships(self) -> pd.DataFrame:
"""Load and return the relationships dataframe with correct types."""
df = await self._table_provider.read_dataframe("relationships")
return relationships_typed(df)
async def communities(self) -> pd.DataFrame:
"""Load and return the communities dataframe with correct types."""
df = await self._table_provider.read_dataframe("communities")
return communities_typed(df)
async def community_reports(self) -> pd.DataFrame:
"""Load and return the community reports dataframe with correct types."""
df = await self._table_provider.read_dataframe("community_reports")
return community_reports_typed(df)
async def covariates(self) -> pd.DataFrame:
"""Load and return the covariates dataframe with correct types."""
df = await self._table_provider.read_dataframe("covariates")
return covariates_typed(df)
async def text_units(self) -> pd.DataFrame:
"""Load and return the text units dataframe with correct types."""
df = await self._table_provider.read_dataframe("text_units")
return text_units_typed(df)
async def documents(self) -> pd.DataFrame:
"""Load and return the documents dataframe with correct types."""
df = await self._table_provider.read_dataframe("documents")
return documents_typed(df)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/data_model/data_reader.py",
"license": "MIT License",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag/graphrag/data_model/dfs.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""A package containing dataframe processing utilities."""
from typing import Any
import pandas as pd
from graphrag.data_model.schemas import (
COMMUNITY_CHILDREN,
COMMUNITY_ID,
COMMUNITY_LEVEL,
COVARIATE_IDS,
EDGE_DEGREE,
EDGE_WEIGHT,
ENTITY_IDS,
FINDINGS,
N_TOKENS,
NODE_DEGREE,
NODE_FREQUENCY,
PERIOD,
RATING,
RELATIONSHIP_IDS,
SHORT_ID,
SIZE,
TEXT_UNIT_IDS,
)
def _safe_int(series: pd.Series, fill: int = -1) -> pd.Series:
"""Convert a series to int, filling NaN values first."""
return series.fillna(fill).astype(int)
def split_list_column(value: Any) -> list[Any]:
r"""Split a column containing a list string into an actual list.
Handles two CSV serialization formats:
- Comma-separated (standard ``str(list)``): ``"['a', 'b']"``
- Newline-separated (pandas ``to_csv`` of numpy arrays):
``"['a'\\n 'b']"``
Both formats are stripped of brackets, quotes, and whitespace so
that existing indexes produced by the old pandas-based indexer
remain readable.
"""
if isinstance(value, str):
if not value:
return []
normalized = value.replace("\n", ",")
items = [item.strip("[] '\"") for item in normalized.split(",")]
return [item for item in items if item]
return value
# Backward-compatible alias so internal callers keep working.
_split_list_column = split_list_column
def entities_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the entities dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = _safe_int(df[SHORT_ID])
if TEXT_UNIT_IDS in df.columns:
df[TEXT_UNIT_IDS] = df[TEXT_UNIT_IDS].apply(_split_list_column)
if NODE_FREQUENCY in df.columns:
df[NODE_FREQUENCY] = _safe_int(df[NODE_FREQUENCY], 0)
if NODE_DEGREE in df.columns:
df[NODE_DEGREE] = _safe_int(df[NODE_DEGREE], 0)
return df
def relationships_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the relationships dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = _safe_int(df[SHORT_ID])
if EDGE_WEIGHT in df.columns:
df[EDGE_WEIGHT] = df[EDGE_WEIGHT].astype(float)
if EDGE_DEGREE in df.columns:
df[EDGE_DEGREE] = _safe_int(df[EDGE_DEGREE], 0)
if TEXT_UNIT_IDS in df.columns:
df[TEXT_UNIT_IDS] = df[TEXT_UNIT_IDS].apply(_split_list_column)
return df
def communities_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the communities dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = df[SHORT_ID].astype(int)
df[COMMUNITY_ID] = df[COMMUNITY_ID].astype(int)
df[COMMUNITY_LEVEL] = df[COMMUNITY_LEVEL].astype(int)
df[COMMUNITY_CHILDREN] = df[COMMUNITY_CHILDREN].apply(_split_list_column)
if ENTITY_IDS in df.columns:
df[ENTITY_IDS] = df[ENTITY_IDS].apply(_split_list_column)
if RELATIONSHIP_IDS in df.columns:
df[RELATIONSHIP_IDS] = df[RELATIONSHIP_IDS].apply(_split_list_column)
if TEXT_UNIT_IDS in df.columns:
df[TEXT_UNIT_IDS] = df[TEXT_UNIT_IDS].apply(_split_list_column)
df[PERIOD] = df[PERIOD].astype(str)
df[SIZE] = df[SIZE].astype(int)
return df
def community_reports_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the community reports dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = df[SHORT_ID].astype(int)
df[COMMUNITY_ID] = df[COMMUNITY_ID].astype(int)
df[COMMUNITY_LEVEL] = df[COMMUNITY_LEVEL].astype(int)
df[COMMUNITY_CHILDREN] = df[COMMUNITY_CHILDREN].apply(_split_list_column)
df[RATING] = df[RATING].astype(float)
df[FINDINGS] = df[FINDINGS].apply(_split_list_column)
df[SIZE] = df[SIZE].astype(int)
return df
def covariates_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the covariates dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = df[SHORT_ID].astype(int)
return df
def text_units_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the text units dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = df[SHORT_ID].astype(int)
df[N_TOKENS] = df[N_TOKENS].astype(int)
if ENTITY_IDS in df.columns:
df[ENTITY_IDS] = df[ENTITY_IDS].apply(_split_list_column)
if RELATIONSHIP_IDS in df.columns:
df[RELATIONSHIP_IDS] = df[RELATIONSHIP_IDS].apply(_split_list_column)
if COVARIATE_IDS in df.columns:
df[COVARIATE_IDS] = df[COVARIATE_IDS].apply(_split_list_column)
return df
def documents_typed(df: pd.DataFrame) -> pd.DataFrame:
"""Return the documents dataframe with correct types, in case it was stored in a weakly-typed format."""
if SHORT_ID in df.columns:
df[SHORT_ID] = df[SHORT_ID].astype(int)
if TEXT_UNIT_IDS in df.columns:
df[TEXT_UNIT_IDS] = df[TEXT_UNIT_IDS].apply(_split_list_column)
return df
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag/graphrag/data_model/dfs.py",
"license": "MIT License",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/csv_table_provider.py | # Copyright (c) 2025 Microsoft Corporation.
# Licensed under the MIT License
"""CSV-based table provider implementation."""
import logging
import re
from io import StringIO
import pandas as pd
from graphrag_storage.file_storage import FileStorage
from graphrag_storage.storage import Storage
from graphrag_storage.tables.csv_table import CSVTable
from graphrag_storage.tables.table import RowTransformer
from graphrag_storage.tables.table_provider import TableProvider
logger = logging.getLogger(__name__)
class CSVTableProvider(TableProvider):
"""Table provider that stores tables as CSV files using an underlying Storage instance.
This provider converts between pandas DataFrames and csv format,
storing the data through a Storage backend (file, blob, cosmos, etc.).
"""
def __init__(self, storage: Storage, **kwargs) -> None:
"""Initialize the CSV table provider with an underlying storage instance.
Args
----
storage: Storage
The storage instance to use for reading and writing csv files.
**kwargs: Any
Additional keyword arguments (currently unused).
"""
if not isinstance(storage, FileStorage):
msg = "CSVTableProvider only works with FileStorage backends for now. "
raise TypeError(msg)
self._storage = storage
async def read_dataframe(self, table_name: str) -> pd.DataFrame:
"""Read a table from storage as a pandas DataFrame.
Args
----
table_name: str
The name of the table to read. The file will be accessed as '{table_name}.csv'.
Returns
-------
pd.DataFrame:
The table data loaded from the csv file.
Raises
------
ValueError:
If the table file does not exist in storage.
Exception:
If there is an error reading or parsing the csv file.
"""
filename = f"{table_name}.csv"
if not await self._storage.has(filename):
msg = f"Could not find {filename} in storage!"
raise ValueError(msg)
try:
logger.info("reading table from storage: %s", filename)
csv_data = await self._storage.get(filename, as_bytes=False)
# Handle empty CSV (pandas can't parse files with no columns)
if not csv_data or csv_data.strip() == "":
return pd.DataFrame()
return pd.read_csv(StringIO(csv_data), keep_default_na=False)
except Exception:
logger.exception("error loading table from storage: %s", filename)
raise
async def write_dataframe(self, table_name: str, df: pd.DataFrame) -> None:
"""Write a pandas DataFrame to storage as a CSV file.
Args
----
table_name: str
The name of the table to write. The file will be saved as '{table_name}.csv'.
df: pd.DataFrame
The DataFrame to write to storage.
"""
await self._storage.set(f"{table_name}.csv", df.to_csv(index=False))
async def has(self, table_name: str) -> bool:
"""Check if a table exists in storage.
Args
----
table_name: str
The name of the table to check.
Returns
-------
bool:
True if the table exists, False otherwise.
"""
return await self._storage.has(f"{table_name}.csv")
def list(self) -> list[str]:
"""List all table names in storage.
Returns
-------
list[str]:
List of table names (without .csv extension).
"""
return [
file.replace(".csv", "")
for file in self._storage.find(re.compile(r"\.csv$"))
]
def open(
self,
table_name: str,
transformer: RowTransformer | None = None,
truncate: bool = True,
encoding: str = "utf-8",
) -> CSVTable:
"""Open table for streaming.
Args:
table_name: Name of the table to open
transformer: Optional callable to transform each row
truncate: If True, truncate file on first write
encoding: Character encoding for reading/writing CSV files.
Defaults to "utf-8".
"""
return CSVTable(
self._storage,
table_name,
transformer=transformer,
truncate=truncate,
encoding=encoding,
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/csv_table_provider.py",
"license": "MIT License",
"lines": 117,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/storage/test_csv_table_provider.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
import unittest
from io import StringIO
import pandas as pd
import pytest
from graphrag_storage import (
StorageConfig,
StorageType,
create_storage,
)
from graphrag_storage.tables.csv_table_provider import CSVTableProvider
class TestCSVTableProvider(unittest.IsolatedAsyncioTestCase):
"""Test suite for CSVTableProvider."""
def setUp(self):
"""Set up test fixtures."""
self.storage = create_storage(
StorageConfig(
type=StorageType.Memory,
)
)
self.table_provider = CSVTableProvider(storage=self.storage)
async def asyncTearDown(self):
"""Clean up after tests."""
await self.storage.clear()
async def test_write_and_read(self):
"""Test writing and reading a DataFrame."""
df = pd.DataFrame({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Charlie"],
"age": [30, 25, 35],
})
await self.table_provider.write_dataframe("users", df)
result = await self.table_provider.read_dataframe("users")
pd.testing.assert_frame_equal(result, df)
async def test_read_nonexistent_table_raises_error(self):
"""Test that reading a nonexistent table raises ValueError."""
with pytest.raises(
ValueError, match=r"Could not find nonexistent\.csv in storage!"
):
await self.table_provider.read_dataframe("nonexistent")
async def test_empty_dataframe(self):
"""Test writing and reading an empty DataFrame."""
df = pd.DataFrame()
await self.table_provider.write_dataframe("empty", df)
result = await self.table_provider.read_dataframe("empty")
pd.testing.assert_frame_equal(result, df)
async def test_dataframe_with_multiple_types(self):
"""Test DataFrame with multiple column types."""
df = pd.DataFrame({
"int_col": [1, 2, 3],
"float_col": [1.1, 2.2, 3.3],
"str_col": ["a", "b", "c"],
"bool_col": [True, False, True],
})
await self.table_provider.write_dataframe("mixed", df)
result = await self.table_provider.read_dataframe("mixed")
pd.testing.assert_frame_equal(result, df)
async def test_storage_persistence(self):
"""Test that data is persisted in underlying storage."""
df = pd.DataFrame({"x": [1, 2, 3]})
await self.table_provider.write_dataframe("test", df)
assert await self.storage.has("test.csv")
csv_data = await self.storage.get("test.csv", as_bytes=False)
loaded_df = pd.read_csv(StringIO(csv_data))
pd.testing.assert_frame_equal(loaded_df, df)
async def test_has(self):
"""Test has() method for checking table existence."""
df = pd.DataFrame({"a": [1, 2, 3]})
# Table doesn't exist yet
assert not await self.table_provider.has("test_table")
# Write the table
await self.table_provider.write_dataframe("test_table", df)
# Now it exists
assert await self.table_provider.has("test_table")
async def test_list(self):
"""Test listing all tables in storage."""
# Initially empty
assert self.table_provider.list() == []
# Create some tables
df1 = pd.DataFrame({"a": [1, 2, 3]})
df2 = pd.DataFrame({"b": [4, 5, 6]})
df3 = pd.DataFrame({"c": [7, 8, 9]})
await self.table_provider.write_dataframe("table1", df1)
await self.table_provider.write_dataframe("table2", df2)
await self.table_provider.write_dataframe("table3", df3)
# List tables
tables = self.table_provider.list()
assert len(tables) == 3
assert set(tables) == {"table1", "table2", "table3"}
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/storage/test_csv_table_provider.py",
"license": "MIT License",
"lines": 90,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/table_provider_config.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Storage configuration model."""
from pydantic import BaseModel, ConfigDict, Field
from graphrag_storage.tables.table_type import TableType
class TableProviderConfig(BaseModel):
"""The default configuration section for table providers."""
model_config = ConfigDict(extra="allow")
"""Allow extra fields to support custom table provider implementations."""
type: str = Field(
description="The table type to use.",
default=TableType.Parquet,
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/table_provider_config.py",
"license": "MIT License",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/table_provider_factory.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Storage factory implementation."""
from collections.abc import Callable
from graphrag_common.factory import Factory, ServiceScope
from graphrag_storage.storage import Storage
from graphrag_storage.tables.table_provider import TableProvider
from graphrag_storage.tables.table_provider_config import TableProviderConfig
from graphrag_storage.tables.table_type import TableType
class TableProviderFactory(Factory[TableProvider]):
"""A factory class for table storage implementations."""
table_provider_factory = TableProviderFactory()
def register_table_provider(
table_type: str,
table_initializer: Callable[..., TableProvider],
scope: ServiceScope = "transient",
) -> None:
"""Register a custom storage implementation.
Args
----
- table_type: str
The table type id to register.
- table_initializer: Callable[..., TableProvider]
The table initializer to register.
"""
table_provider_factory.register(table_type, table_initializer, scope)
def create_table_provider(
config: TableProviderConfig, storage: Storage | None = None
) -> TableProvider:
"""Create a table provider implementation based on the given configuration.
Args
----
- config: TableProviderConfig
The table provider configuration to use.
- storage: Storage | None
The storage implementation to use for file-based TableProviders such as Parquet and CSV.
Returns
-------
TableProvider
The created table provider implementation.
"""
config_model = config.model_dump()
table_type = config.type
if table_type not in table_provider_factory:
match table_type:
case TableType.Parquet:
from graphrag_storage.tables.parquet_table_provider import (
ParquetTableProvider,
)
register_table_provider(TableType.Parquet, ParquetTableProvider)
case TableType.CSV:
from graphrag_storage.tables.csv_table_provider import (
CSVTableProvider,
)
register_table_provider(TableType.CSV, CSVTableProvider)
case _:
msg = f"TableProviderConfig.type '{table_type}' is not registered in the TableProviderFactory. Registered types: {', '.join(table_provider_factory.keys())}."
raise ValueError(msg)
if storage:
config_model["storage"] = storage
return table_provider_factory.create(table_type, config_model)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/table_provider_factory.py",
"license": "MIT License",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/table_type.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Builtin table storage implementation types."""
from enum import StrEnum
class TableType(StrEnum):
"""Enum for table storage types."""
Parquet = "parquet"
CSV = "csv"
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/table_type.py",
"license": "MIT License",
"lines": 8,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/parquet_table_provider.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Parquet-based table provider implementation."""
import logging
import re
from io import BytesIO
import pandas as pd
from graphrag_storage.storage import Storage
from graphrag_storage.tables.parquet_table import ParquetTable
from graphrag_storage.tables.table import RowTransformer, Table
from graphrag_storage.tables.table_provider import TableProvider
logger = logging.getLogger(__name__)
class ParquetTableProvider(TableProvider):
"""Table provider that stores tables as Parquet files using an underlying Storage instance.
This provider converts between pandas DataFrames and Parquet format,
storing the data through a Storage backend (file, blob, cosmos, etc.).
"""
def __init__(self, storage: Storage, **kwargs) -> None:
"""Initialize the Parquet table provider with an underlying storage instance.
Args
----
storage: Storage
The storage instance to use for reading and writing Parquet files.
**kwargs: Any
Additional keyword arguments (currently unused).
"""
self._storage = storage
async def read_dataframe(self, table_name: str) -> pd.DataFrame:
"""Read a table from storage as a pandas DataFrame.
Args
----
table_name: str
The name of the table to read. The file will be accessed as '{table_name}.parquet'.
Returns
-------
pd.DataFrame:
The table data loaded from the Parquet file.
Raises
------
ValueError:
If the table file does not exist in storage.
Exception:
If there is an error reading or parsing the Parquet file.
"""
filename = f"{table_name}.parquet"
if not await self._storage.has(filename):
msg = f"Could not find {filename} in storage!"
raise ValueError(msg)
try:
logger.info("reading table from storage: %s", filename)
return pd.read_parquet(
BytesIO(await self._storage.get(filename, as_bytes=True))
)
except Exception:
logger.exception("error loading table from storage: %s", filename)
raise
async def write_dataframe(self, table_name: str, df: pd.DataFrame) -> None:
"""Write a pandas DataFrame to storage as a Parquet file.
Args
----
table_name: str
The name of the table to write. The file will be saved as '{table_name}.parquet'.
df: pd.DataFrame
The DataFrame to write to storage.
"""
await self._storage.set(f"{table_name}.parquet", df.to_parquet())
async def has(self, table_name: str) -> bool:
"""Check if a table exists in storage.
Args
----
table_name: str
The name of the table to check.
Returns
-------
bool:
True if the table exists, False otherwise.
"""
return await self._storage.has(f"{table_name}.parquet")
def list(self) -> list[str]:
"""List all table names in storage.
Returns
-------
list[str]:
List of table names (without .parquet extension).
"""
return [
file.replace(".parquet", "")
for file in self._storage.find(re.compile(r"\.parquet$"))
]
def open(
self,
table_name: str,
transformer: RowTransformer | None = None,
truncate: bool = True,
) -> Table:
"""Open a table for streaming row operations.
Returns a ParquetTable that simulates streaming by loading the
DataFrame and iterating rows, or accumulating writes for batch output.
Args
----
table_name: str
The name of the table to open.
transformer: RowTransformer | None
Optional callable to transform each row on read.
truncate: bool
If True (default), overwrite existing file on close.
If False, append new rows to existing file.
Returns
-------
Table:
A ParquetTable instance for row-by-row access.
"""
return ParquetTable(self._storage, table_name, transformer, truncate=truncate)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/parquet_table_provider.py",
"license": "MIT License",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-storage/graphrag_storage/tables/table_provider.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Abstract base class for table providers."""
from abc import ABC, abstractmethod
from typing import Any
import pandas as pd
from graphrag_storage.tables.table import RowTransformer, Table
class TableProvider(ABC):
"""Provide a table-based storage interface with support for DataFrames and row dictionaries."""
@abstractmethod
def __init__(self, **kwargs: Any) -> None:
"""Create a table provider instance.
Args
----
**kwargs: Any
Keyword arguments for initialization, may include underlying Storage instance.
"""
@abstractmethod
async def read_dataframe(self, table_name: str) -> pd.DataFrame:
"""Read entire table as a pandas DataFrame.
Args
----
table_name: str
The name of the table to read.
Returns
-------
pd.DataFrame:
The table data as a DataFrame.
"""
@abstractmethod
async def write_dataframe(self, table_name: str, df: pd.DataFrame) -> None:
"""Write entire table from a pandas DataFrame.
Args
----
table_name: str
The name of the table to write.
df: pd.DataFrame
The DataFrame to write as a table.
"""
@abstractmethod
async def has(self, table_name: str) -> bool:
"""Check if a table exists in the provider.
Args
----
table_name: str
The name of the table to check.
Returns
-------
bool:
True if the table exists, False otherwise.
"""
@abstractmethod
def list(self) -> list[str]:
"""List all table names in the provider.
Returns
-------
list[str]:
List of table names (without file extensions).
"""
@abstractmethod
def open(
self,
table_name: str,
transformer: RowTransformer | None = None,
truncate: bool = True,
) -> Table: # Returns Table instance
"""Open a table for row-by-row streaming operations.
Args
----
table_name: str
The name of the table to open.
transformer: RowTransformer | None
Optional transformer function to apply to each row.
truncate: bool
If True (default), truncate existing file on first write.
If False, append rows to existing file (DB-like behavior).
Returns
-------
Table:
A Table instance for streaming row operations.
"""
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-storage/graphrag_storage/tables/table_provider.py",
"license": "MIT License",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:tests/unit/storage/test_parquet_table_provider.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
import unittest
from io import BytesIO
import pandas as pd
import pytest
from graphrag_storage import (
StorageConfig,
StorageType,
create_storage,
)
from graphrag_storage.tables.parquet_table_provider import ParquetTableProvider
class TestParquetTableProvider(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.storage = create_storage(
StorageConfig(
type=StorageType.Memory,
)
)
self.table_provider = ParquetTableProvider(storage=self.storage)
async def asyncTearDown(self):
await self.storage.clear()
async def test_write_and_read(self):
df = pd.DataFrame({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Charlie"],
"age": [30, 25, 35],
})
await self.table_provider.write_dataframe("users", df)
result = await self.table_provider.read_dataframe("users")
pd.testing.assert_frame_equal(result, df)
async def test_read_nonexistent_table_raises_error(self):
with pytest.raises(
ValueError, match=r"Could not find nonexistent\.parquet in storage!"
):
await self.table_provider.read_dataframe("nonexistent")
async def test_empty_dataframe(self):
df = pd.DataFrame()
await self.table_provider.write_dataframe("empty", df)
result = await self.table_provider.read_dataframe("empty")
pd.testing.assert_frame_equal(result, df)
async def test_dataframe_with_multiple_types(self):
df = pd.DataFrame({
"int_col": [1, 2, 3],
"float_col": [1.1, 2.2, 3.3],
"str_col": ["a", "b", "c"],
"bool_col": [True, False, True],
})
await self.table_provider.write_dataframe("mixed", df)
result = await self.table_provider.read_dataframe("mixed")
pd.testing.assert_frame_equal(result, df)
async def test_storage_persistence(self):
df = pd.DataFrame({"x": [1, 2, 3]})
await self.table_provider.write_dataframe("test", df)
assert await self.storage.has("test.parquet")
parquet_bytes = await self.storage.get("test.parquet", as_bytes=True)
loaded_df = pd.read_parquet(BytesIO(parquet_bytes))
pd.testing.assert_frame_equal(loaded_df, df)
async def test_has(self):
df = pd.DataFrame({"a": [1, 2, 3]})
# Table doesn't exist yet
assert not await self.table_provider.has("test_table")
# Write the table
await self.table_provider.write_dataframe("test_table", df)
# Now it exists
assert await self.table_provider.has("test_table")
| {
"repo_id": "microsoft/graphrag",
"file_path": "tests/unit/storage/test_parquet_table_provider.py",
"license": "MIT License",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
microsoft/graphrag:packages/graphrag-cache/graphrag_cache/cache_config.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Cache configuration model."""
from graphrag_storage import StorageConfig, StorageType
from pydantic import BaseModel, ConfigDict, Field
from graphrag_cache.cache_type import CacheType
class CacheConfig(BaseModel):
"""The configuration section for cache."""
model_config = ConfigDict(extra="allow")
"""Allow extra fields to support custom cache implementations."""
type: str = Field(
description="The cache type to use. Builtin types include 'Json', 'Memory', and 'Noop'.",
default=CacheType.Json,
)
storage: StorageConfig | None = Field(
description="The storage configuration to use for file-based caches such as 'Json'.",
default_factory=lambda: StorageConfig(type=StorageType.File, base_dir="cache"),
)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-cache/graphrag_cache/cache_config.py",
"license": "MIT License",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-cache/graphrag_cache/cache_factory.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Cache factory implementation."""
from collections.abc import Callable
from graphrag_common.factory import Factory, ServiceScope
from graphrag_storage import Storage, create_storage
from graphrag_cache.cache import Cache
from graphrag_cache.cache_config import CacheConfig
from graphrag_cache.cache_type import CacheType
class CacheFactory(Factory["Cache"]):
"""A factory class for cache implementations."""
cache_factory = CacheFactory()
def register_cache(
cache_type: str,
cache_initializer: Callable[..., Cache],
scope: ServiceScope = "transient",
) -> None:
"""Register a custom cache implementation.
Args
----
- cache_type: str
The cache id to register.
- cache_initializer: Callable[..., Cache]
The cache initializer to register.
"""
cache_factory.register(cache_type, cache_initializer, scope)
def create_cache(
config: CacheConfig | None = None, storage: Storage | None = None
) -> "Cache":
"""Create a cache implementation based on the given configuration.
Args
----
- config: CacheConfig
The cache configuration to use.
- storage: Storage | None
The storage implementation to use for file-based caches such as 'Json'.
Returns
-------
Cache
The created cache implementation.
"""
config = config or CacheConfig()
config_model = config.model_dump()
cache_strategy = config.type
if not storage and config.storage:
storage = create_storage(config.storage)
if cache_strategy not in cache_factory:
match cache_strategy:
case CacheType.Json:
from graphrag_cache.json_cache import JsonCache
register_cache(CacheType.Json, JsonCache)
case CacheType.Memory:
from graphrag_cache.memory_cache import MemoryCache
register_cache(CacheType.Memory, MemoryCache)
case CacheType.Noop:
from graphrag_cache.noop_cache import NoopCache
register_cache(CacheType.Noop, NoopCache)
case _:
msg = f"CacheConfig.type '{cache_strategy}' is not registered in the CacheFactory. Registered types: {', '.join(cache_factory.keys())}."
raise ValueError(msg)
if storage:
config_model["storage"] = storage
return cache_factory.create(strategy=cache_strategy, init_args=config_model)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-cache/graphrag_cache/cache_factory.py",
"license": "MIT License",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-cache/graphrag_cache/cache_key.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Create cache key."""
from typing import Any, Protocol, runtime_checkable
from graphrag_common.hasher import hash_data
@runtime_checkable
class CacheKeyCreator(Protocol):
"""Create cache key function protocol.
Args
----
input_args: dict[str, Any]
The input arguments for creating the cache key.
Returns
-------
str
The generated cache key.
"""
def __call__(
self,
input_args: dict[str, Any],
) -> str:
"""Create cache key."""
...
def create_cache_key(input_args: dict[str, Any]) -> str:
"""Create a cache key based on the input arguments."""
return hash_data(input_args)
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-cache/graphrag_cache/cache_key.py",
"license": "MIT License",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
microsoft/graphrag:packages/graphrag-cache/graphrag_cache/cache_type.py | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""Builtin cache implementation types."""
from enum import StrEnum
class CacheType(StrEnum):
"""Enum for cache types."""
Json = "json"
Memory = "memory"
Noop = "none"
| {
"repo_id": "microsoft/graphrag",
"file_path": "packages/graphrag-cache/graphrag_cache/cache_type.py",
"license": "MIT License",
"lines": 9,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.