repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
Retrieval-based-Voice-Conversion-WebUI | infer/hubert.py | .py | import logging
from functools import lru_cache
from pathlib import Path
import torch
from torch import nn
from transformers import AutoFeatureExtractor, HubertModel
from tools.cuda_graph import run_cuda_graph
logger = logging.getLogger(__name__)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
class HubertM... | 128 | 4,148 |
Retrieval-based-Voice-Conversion-WebUI | infer/rtrvc.py | .py | import traceback
from time import time as ttime
import faiss
import numpy as np
import parselmouth
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio.transforms import Resample
from infer.hubert import extract_hubert_features, load_hubert_model
from i18n.i18n import I18nAuto
from tools.... | 366 | 13,556 |
Retrieval-based-Voice-Conversion-WebUI | infer/module/commons.py | .py | from typing import List, Optional
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_... | 172 | 5,463 |
Retrieval-based-Voice-Conversion-WebUI | infer/module/models.py | .py | import math
import logging
from typing import Optional
logger = logging.getLogger(__name__)
import numpy as np
import torch
from torch import nn
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn import functional as F
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor... | 1,095 | 35,798 |
Retrieval-based-Voice-Conversion-WebUI | infer/module/attentions.py | .py | import copy
import math
from typing import Optional
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from infer.module import commons, modules
from infer.module.modules import LayerNorm
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
... | 460 | 15,994 |
Retrieval-based-Voice-Conversion-WebUI | infer/module/modules.py | .py | import copy
import math
from typing import Optional, Tuple
import numpy as np
import scipy
import torch
from torch import nn
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn import functional as F
from torch.nn.utils import remove_weight_norm, weight_norm
from infer.module import commons
... | 549 | 17,775 |
Retrieval-based-Voice-Conversion-WebUI | infer/module/transforms.py | .py | import numpy as np
import torch
from torch.nn import functional as F
DEFAULT_MIN_BIN_WIDTH = 1e-3
DEFAULT_MIN_BIN_HEIGHT = 1e-3
DEFAULT_MIN_DERIVATIVE = 1e-3
def piecewise_rational_quadratic_transform(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
... | 208 | 7,458 |
Retrieval-based-Voice-Conversion-WebUI | infer/vc/pipeline.py | .py | import os
import traceback
import logging
logger = logging.getLogger(__name__)
from time import time as ttime
import faiss
import librosa
import numpy as np
import parselmouth
import torch
import torch.nn.functional as F
from scipy import signal
from infer.hubert import extract_hubert_features
from tools.cuda_graph... | 411 | 14,248 |
Retrieval-based-Voice-Conversion-WebUI | infer/vc/utils.py | .py | import os
import re
from infer.hubert import load_hubert_model
def get_index_path_from_model(sid, speaker_id=None):
model_stem = os.path.splitext(os.path.basename(str(sid or "")))[0]
experiment_name = re.sub(r"_e\d+_s\d+$", "", model_stem, flags=re.IGNORECASE)
if not experiment_name:
return ""
... | 62 | 2,663 |
Retrieval-based-Voice-Conversion-WebUI | infer/vc/modules.py | .py | import traceback
import logging
logger = logging.getLogger(__name__)
import numpy as np
import soundfile as sf
import torch
from io import BytesIO
from infer.audio import load_audio, wav2
from infer.module.models import (
SynthesizerTrnMs256NSFsid,
SynthesizerTrnMs256NSFsid_nono,
SynthesizerTrnMs768NSFsi... | 428 | 14,565 |
Retrieval-based-Voice-Conversion-WebUI | configs/config.py | .py | import argparse
import os
import re
import sys
import json
from multiprocessing import cpu_count
from pathlib import Path
from tools.file_io import read_text
import torch
import logging
from tools.cuda_graph import configure_cuda_graph
logger = logging.getLogger(__name__)
# Keep device/precision eligibility in one... | 287 | 9,111 |
Retrieval-based-Voice-Conversion-WebUI | RVCRealtimeVST/worker/rvc_worker.py | .py | """RVC inference worker for the RVC Realtime VST2/VST3 plugin."""
from __future__ import annotations
import argparse
import ctypes
import json
import mmap
import os
import struct
import sys
import time
import traceback
from pathlib import Path
MAGIC = 0x50564352
PROTOCOL_VERSION = 1
HEADER_BYTES = 4096
MAX_FRAMES = ... | 346 | 14,493 |
Kronos | webui/app.py | .py | import os
import pandas as pd
import numpy as np
import json
import plotly.graph_objects as go
import plotly.utils
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import sys
import warnings
import datetime
warnings.filterwarnings('ignore')
# Add project root directory to path
sys... | 709 | 30,464 |
Kronos | webui/run.py | .py | #!/usr/bin/env python3
"""
Kronos Web UI startup script
"""
import os
import sys
import subprocess
import webbrowser
import time
def check_dependencies():
"""Check if dependencies are installed"""
try:
import flask
import flask_cors
import pandas
import numpy
import plo... | 90 | 2,608 |
Kronos | model/__init__.py | .py | from .kronos import KronosTokenizer, Kronos, KronosPredictor
model_dict = {
'kronos_tokenizer': KronosTokenizer,
'kronos': Kronos,
'kronos_predictor': KronosPredictor
}
def get_model_class(model_name):
if model_name in model_dict:
return model_dict[model_name]
else:
print(f"Model ... | 18 | 412 |
Kronos | model/module.py | .py | import math
from einops import rearrange, reduce
import torch
import torch.nn as nn
from torch.autograd import Function
import torch.nn.functional as F
class DifferentiableEntropyFunction(Function):
@staticmethod
def forward(ctx, zq, basis, K, eps):
zb = (zq + 1) / 2
zi = ((zb * basis).sum(-1... | 571 | 23,426 |
Kronos | model/kronos.py | .py | import numpy as np
import pandas as pd
import torch
from huggingface_hub import PyTorchModelHubMixin
import sys
from tqdm import trange
sys.path.append("../")
from model.module import *
class KronosTokenizer(nn.Module, PyTorchModelHubMixin):
"""
KronosTokenizer module for tokenizing input data using a hybri... | 663 | 30,133 |
Kronos | tests/test_kronos_regression.py | .py | import random
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
import torch
from tqdm import tqdm
from model import Kronos, KronosPredictor, KronosTokenizer
TEST_DATA_ROOT = Path(__file__).parent / "data"
INPUT_DATA_PATH = TEST_DATA_ROOT / "regression_input.csv"
# Regression test config... | 141 | 5,326 |
Kronos | tests/data/generate_regression_output.py | .py | import random
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from model import Kronos, KronosPredictor, KronosTokenizer
TEST_DATA_ROOT = Path(__file__).parent
INPUT_DATA_PATH = TEST_DATA_ROOT / "regression_input.csv"
OUTPUT_DATA_DIR = TEST_DATA_ROOT
MAX_CTX_LEN = 512
TEST_CTX_LEN = [51... | 92 | 2,814 |
Kronos | finetune_csv/finetune_base_model.py | .py | import os
import sys
import json
import time
import pickle
import random
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
from time import gmtime, strftime
import logging
from logging.ha... | 469 | 19,127 |
Kronos | finetune_csv/config_loader.py | .py | import os
import yaml
from typing import Dict, Any
class ConfigLoader:
def __init__(self, config_path: str):
self.config_path = config_path
self.config = self._load_config()
def _load_config(self) -> Dict[str, Any]:
if not os.path.exists(self.config_path):
raise... | 268 | 11,688 |
Kronos | finetune_csv/train_sequential.py | .py | import os
import sys
import time
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.distributed as dist
sys.path.append('../')
from model import Kronos, KronosTokenizer, KronosPredictor
from config_loader import CustomFinetuneConfig
from finetune_tokenizer import t... | 362 | 15,358 |
Kronos | finetune_csv/finetune_tokenizer.py | .py | import os
import sys
import json
import time
import random
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from time import gmtime, strftime
import datetime
import logging
from logging.handlers import Rot... | 360 | 13,741 |
Kronos | examples/run_backtest_kronos.py | .py | # run_backtest.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class KronosBacktester:
"... | 455 | 16,811 |
Kronos | examples/prediction_cn_markets_day.py | .py | # -*- coding: utf-8 -*-
"""
prediction_cn_markets_day.py
Description:
Predicts future daily K-line (1D) data for A-share markets using Kronos model and akshare.
The script automatically downloads the latest historical data, cleans it, and runs model inference.
Usage:
python prediction_cn_markets_day.py --... | 209 | 6,514 |
Kronos | examples/get_date_new.py | .py | import pandas as pd
import requests
import json
from datetime import datetime, timedelta
import os
import time
import random
def get_stock_market(stock_code):
"""
根据股票代码判断市场类型
返回: 市场前缀 '0'-深交所, '1'-上交所
"""
if stock_code.startswith(('0', '2', '3')):
return '0' # 深交所
elif stock_code.sta... | 661 | 24,268 |
Kronos | examples/prediction_batch_example.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import sys
sys.path.append("../")
from model import Kronos, KronosTokenizer, KronosPredictor
def plot_prediction(kline_df, pred_df):
pred_df.index = kline_df.index[-pred_df.shape[0]:]
sr_close = kline_df['close']
sr_pred_close = pred_df['close']
sr_c... | 73 | 2,312 |
Kronos | examples/prediction_new.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
from datetime import datetime, timedelta
import warnings
import requests
import json
import time
import random
import akshare as ak
from typing import Dict, List, Tuple, Optional
warnings.filterwarnings('ignore')
# 添加项目路径以便导入自... | 1,333 | 52,593 |
Kronos | examples/prediction_akshare_2024-2025.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# 添加项目路径以便导入自定义模块
sys.path.append("../")
from model import Kronos, KronosTokenizer, KronosPredictor
# 设置中文字体
plt.rcParams['font.sans-s... | 545 | 22,647 |
Kronos | examples/prediction_example.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import sys
sys.path.append("../")
from model import Kronos, KronosTokenizer, KronosPredictor
def plot_prediction(kline_df, pred_df):
pred_df.index = kline_df.index[-pred_df.shape[0]:]
sr_close = kline_df['close']
sr_pred_close = pred_df['close']
sr_c... | 81 | 2,457 |
Kronos | examples/prediction_new_GUI.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
from datetime import datetime, timedelta
import warnings
import requests
import json
import time
import random
import akshare as ak
from typing import Dict, List, Tuple, Optional
import tkinter as tk
from tkinter import ttk, mes... | 1,625 | 65,400 |
Kronos | examples/get_akshare_date_2024-2025_x.py | .py | import pandas as pd
import requests
import json
from datetime import datetime, timedelta
import os
import time
import random
def get_stock_market(stock_code):
"""
根据股票代码判断市场类型
返回: 市场前缀 '0'-深交所, '1'-上交所
"""
if stock_code.startswith(('0', '2', '3')):
return '0' # 深交所
elif stock_code.sta... | 629 | 22,761 |
Kronos | examples/prediction_wo_vol_example.py | .py | import pandas as pd
import matplotlib.pyplot as plt
import sys
sys.path.append("../")
from model import Kronos, KronosTokenizer, KronosPredictor
def plot_prediction(kline_df, pred_df):
pred_df.index = kline_df.index[-pred_df.shape[0]:]
sr_close = kline_df['close']
sr_pred_close = pred_df['close']
sr_c... | 69 | 1,918 |
Kronos | examples/yuce/historical_backtest.py | .py | # historical_backtest.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class HistoricalBackte... | 384 | 14,807 |
Kronos | finetune/train_predictor.py | .py | import os
import sys
import json
import time
from time import gmtime, strftime
import torch.distributed as dist
import torch
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torch.nn.parallel import DistributedDataParallel as DDP
import comet_ml
# Ensure project... | 245 | 10,026 |
Kronos | finetune/qlib_data_preprocess.py | .py | import os
import pickle
import numpy as np
import pandas as pd
import qlib
from qlib.config import REG_CN
from qlib.data import D
from qlib.data.dataset.loader import QlibDataLoader
from tqdm import trange
from config import Config
class QlibDataPreprocessor:
"""
A class to handle the loading, processing, an... | 131 | 5,645 |
Kronos | finetune/train_tokenizer.py | .py | import os
import sys
import json
import time
from time import gmtime, strftime
import argparse
import datetime
import torch.distributed as dist
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torch.nn.parallel import D... | 282 | 11,455 |
Kronos | finetune/dataset.py | .py | import pickle
import random
import numpy as np
import torch
from torch.utils.data import Dataset
from config import Config
class QlibDataset(Dataset):
"""
A PyTorch Dataset for handling Qlib financial time series data.
This dataset pre-computes all possible start indices for sliding windows
and then ... | 139 | 5,434 |
Kronos | finetune/config.py | .py | import os
class Config:
"""
Configuration class for the entire project.
"""
def __init__(self):
# =================================================================
# Data & Feature Parameters
# =================================================================
# TODO: Up... | 132 | 6,247 |
Kronos | finetune/qlib_test.py | .py | import os
import sys
import argparse
import pickle
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from tqdm import trange, tqdm
from matplotlib import pyplot as plt
import qlib
from qlib.config import REG_CN
from qlib.backtest i... | 363 | 15,140 |
Kronos | finetune/utils/training_utils.py | .py | import os
import random
import datetime
import numpy as np
import torch
import torch.distributed as dist
def setup_ddp():
"""
Initializes the distributed data parallel environment.
This function relies on environment variables set by `torchrun` or a similar
launcher. It initializes the process group ... | 119 | 3,830 |
dspy | docs/hooks/fetch_stats.py | .py | """MkDocs hook: fetch live stats at build time and inject into config.extra.stats.
Hits GitHub, PyPI, and Discord APIs once per build. Results are cached to
.cache/stats.json for 1 hour so dev-server rebuilds don't hammer rate limits.
Falls back to cached (or hardcoded) values on any API failure.
"""
import json
impo... | 185 | 5,454 |
dspy | docs/docs/tutorials/dataframe_rlm/cohort_analysis/dataframe.py | .py | """Standalone DataFrame wrapper with RLM sandbox support.
This module provides a DataFrame class that subclasses dspy.SandboxSerializable,
allowing pandas DataFrames to be injected into the RLM sandbox for code execution.
Usage with RLM:
import dspy
from dataframe import DataFrame
rlm = dspy.RLM("data, ... | 103 | 3,480 |
dspy | docs/docs/tutorials/dataframe_rlm/cohort_analysis/generate_cohort_data.py | .py | """Generate a realistic cohort analysis dataset (>5MB) for RLM + DataFrame testing.
Creates three DataFrames mimicking a SaaS product:
- users: 10,000 users with signup info and acquisition channels
- events: ~500,000 feature usage events
- subscriptions: 10,000 subscription records with churn pat... | 192 | 6,963 |
dspy | docs/scripts/generate_api_docs.py | .py | import importlib
import inspect
import pkgutil
from pathlib import Path
from typing import Any
import dspy
API_MAPPING = {
"models": [
dspy.LM,
dspy.Embedder,
],
"primitives": [
dspy.Audio,
dspy.Code,
dspy.Example,
dspy.Image,
dspy.History,
d... | 417 | 13,745 |
dspy | docs/scripts/generate_api_summary.py | .py | from pathlib import Path
INDEX_NAME = {
"models": "Models",
"primitives": "Primitives",
"signatures": "Signatures",
"adapters": "Adapters",
"modules": "Modules",
"evaluation": "Evaluation",
"optimizers": "Optimizers",
"utils": "Utils",
"tools": "Tools",
"experimental": "Experime... | 139 | 4,059 |
dspy | tests/mock_interpreter.py | .py | """
Mock interpreter for testing RLM and other code-executing modules.
This interpreter doesn't actually execute code - it returns scripted responses
or uses a custom function to generate responses. Useful for:
- Unit testing without Deno/Pyodide dependencies
- Testing specific execution paths (errors, SUBMIT, etc.)
-... | 151 | 4,923 |
dspy | tests/conftest.py | .py | import copy
import os
from collections.abc import Iterator
from typing import Any
import pytest
from tests.test_utils.server import ( # noqa: F401
_litellm_test_server,
litellm_test_server,
read_litellm_test_server_request_logs,
)
SKIP_DEFAULT_FLAGS = ["reliability", "extra", "llm_call", "deno"]
def _... | 157 | 4,896 |
dspy | tests/flex/test_flex_gepa_seed.py | .py | """GEPA re-optimization seeds from the module's CURRENT source (incl. manual edits).
When a user edits a flexed module (or re-runs GEPA on a previously-optimized one) and
optimizes again, GEPA must build on the current implementation rather than starting over.
``GEPA.compile`` constructs each flex submodule's seed can... | 62 | 2,376 |
dspy | tests/flex/test_flex_interpreter.py | .py | """dspy.Flex(interpreter_factory=...) runs generated code inside a sandbox via the run-in-interpreter bridge.
Two layers of coverage:
* Unit (no Deno): the interpreter_factory is validated; the host-side bridge callbacks
(``_Invocation.construct``/``.call``) build real predictors on the host, keep them in a
per-f... | 855 | 37,264 |
dspy | tests/flex/_offstack_types.py | .py | """A signature with a custom output type, defined away from the test module that uses it.
dspy resolves a type named in a signature string by walking caller frames for the bare name. Test
modules normally define their types at module scope, which puts them on the stack and hides that
lookup's limits. Importing *this* ... | 27 | 875 |
dspy | tests/flex/test_flex_output_types.py | .py | """dspy.Flex honours its signature's declared output types.
Everything the generated code returns crosses the sandbox boundary as JSON, so a field declared
`int`, `list[str]`, or a pydantic model would otherwise come back to the caller as a bare string or
dict — unlike every other module over the same signature. Two h... | 463 | 18,813 |
dspy | tests/flex/test_flex_binding.py | .py | """dspy.Flex binds a module's source (``module_src``) and makes it usable like any dspy.Module.
Binding a source — the deterministic baseline at construction, or a GEPA-optimized decomposition —
records it host-side (a syntax check, no interpreter); each forward runs it in a fresh sandbox,
constructing its predictors ... | 324 | 13,728 |
dspy | tests/flex/test_flex_gepa.py | .py | """Tests for dspy.Flex code optimization inside dspy.GEPA.
Covers the behavior:
- a freshly constructed dspy.Flex binds a deterministic, LM-free baseline (a dspy.Module subclass;
a single dspy.Predict when no tools are given),
- code-optimizable submodules are discovered by type (dspy.Flex), not by a duck-typed mark... | 542 | 22,095 |
dspy | tests/flex/test_tools.py | .py | """dspy.Flex accepts tools, hands them to the underlying RLM baseline, exposes them to the
GEPA code proposer, and round-trips them through save/load.
Tools are callables/dspy.Tool objects — they are NOT serialized. Like the signature, they are
re-provided at construction; the saved ``module_src`` references them by n... | 304 | 12,397 |
dspy | tests/evaluate/test_metrics.py | .py | # FILEPATH: /Users/ahle/repos/dspy/tests/evaluate/test_metrics.py
import dspy
from dspy.evaluate.metrics import answer_exact_match
from dspy.predict import Predict
def test_answer_exact_match_string():
example = dspy.Example(
question="What is 1+1?",
answer="2",
).with_inputs("question")
... | 36 | 955 |
dspy | tests/evaluate/test_evaluate.py | .py | import json
import signal
import tempfile
import threading
from unittest.mock import patch
import pytest
import dspy
from dspy.evaluate.evaluate import Evaluate, EvaluationResult
from dspy.evaluate.metrics import answer_exact_match
from dspy.predict import Predict
from dspy.utils.callback import ACTIVE_CALL_ID, BaseC... | 464 | 14,524 |
dspy | tests/evaluate/test_auto_evaluation.py | .py | import dspy
from dspy.evaluate.auto_evaluation import CompleteAndGrounded, SemanticF1
from dspy.primitives.prediction import Prediction
from dspy.utils.dummies import DummyLM
def test_semantic_f1_returns_prediction_without_trace():
# Configure with a dummy LM that returns precision and recall values
# ChainOf... | 192 | 5,828 |
dspy | tests/streaming/test_streaming.py | .py | import asyncio
import time
from dataclasses import dataclass
from unittest import mock
from unittest.mock import AsyncMock
import anyio.from_thread
import pydantic
import pytest
from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
import dspy
from dspy.adapters.types import Type
from dspy.expe... | 2,064 | 100,205 |
dspy | tests/signatures/test_custom_types.py | .py |
import pydantic
import pytest
import dspy
from dspy import Signature
def test_basic_custom_type_resolution():
"""Test basic custom type resolution with both explicit and automatic mapping."""
class CustomType(pydantic.BaseModel):
value: str
# Custom types can be explicitly mapped
explicit_s... | 147 | 5,662 |
dspy | tests/signatures/test_adapter_file.py | .py | import os
import tempfile
import pydantic
import pytest
import dspy
from dspy.adapters.types.file import encode_file_to_dict
from dspy.utils.dummies import DummyLM
@pytest.fixture
def sample_text_file():
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp_file:
tmp_file.write(... | 290 | 10,034 |
dspy | tests/signatures/test_adapter_image.py | .py | import base64
import os
import tempfile
import warnings
from io import BytesIO
import pydantic
import pytest
import requests
from PIL import Image as PILImage
import dspy
from dspy.adapters.types.image import encode_image
from dspy.utils.dummies import DummyLM
@pytest.fixture
def sample_pil_image():
"""Fixture ... | 569 | 21,779 |
dspy | tests/signatures/test_signature.py | .py | import pickle
from types import UnionType
from typing import Any, Optional, Union
import cloudpickle
import pydantic
import pytest
import dspy
from dspy import InputField, OutputField, Signature, infer_prefix
from dspy.utils.dummies import DummyLM
def test_field_types_and_custom_attributes():
class TestSignatur... | 641 | 23,925 |
dspy | tests/teleprompt/test_knn_fewshot.py | .py | import pytest
import dspy
from dspy.teleprompt.knn_fewshot import KNNFewShot
from dspy.utils.dummies import DummyLM, DummyVectorizer
def mock_example(question: str, answer: str) -> dspy.Example:
"""Creates a mock DSP example with specified question and answer."""
return dspy.Example(question=question, answer... | 67 | 2,779 |
dspy | tests/teleprompt/test_bettertogether.py | .py | """BetterTogether optimizer tests.
Most of the code in this test file was LLM-generated but has been verified
to correctly test the BetterTogether optimizer functionality.
"""
from unittest.mock import Mock, patch
import pytest
import dspy
from dspy import Example
from dspy.predict import Predict
from dspy.telepromp... | 745 | 30,895 |
dspy | tests/teleprompt/test_bootstrap_finetune.py | .py | from unittest.mock import patch
import dspy
from dspy import Example
from dspy.predict import Predict
from dspy.teleprompt import BootstrapFinetune
from dspy.utils.dummies import DummyLM
# Define a simple metric function for testing
def simple_metric(example, prediction, trace=None):
return example.output == pre... | 125 | 4,236 |
dspy | tests/teleprompt/test_grpo.py | .py | from dspy.teleprompt.grpo import GRPO
def test_grpo_dataset_shuffler():
dataset = [1, 2, 3]
grpo = GRPO(
num_dspy_examples_per_grpo_step=3,
exclude_demos=True,
)
trainset_instances = []
for i in range(4):
trainset_instances.append(grpo.select_training_sample_and_update_shu... | 69 | 1,911 |
dspy | tests/teleprompt/test_copro_optimizer.py | .py | import dspy
from dspy import Example
from dspy.teleprompt.signature_opt import COPRO
from dspy.utils.dummies import DummyLM
# Define a simple metric function for testing
def simple_metric(example, prediction):
# Simplified metric for testing: true if prediction matches expected output
return example.output ==... | 179 | 6,965 |
dspy | tests/teleprompt/test_gepa_instruction_proposer.py | .py | import logging
from dataclasses import dataclass
from typing import Any
import pytest
import dspy
from dspy.teleprompt.gepa import instruction_proposal
from dspy.utils.dummies import DummyLM
def count_messages_with_image_url_pattern(messages):
"""Helper to count image URLs in messages - borrowed from image adap... | 371 | 13,802 |
dspy | tests/teleprompt/test_bootstrap_trace.py | .py | from typing import Any, ClassVar
from unittest import mock
from litellm import Choices, Message, ModelResponse
import dspy
from dspy.primitives.example import Example
from dspy.teleprompt.bootstrap_trace import FailedPrediction, bootstrap_trace_data
def test_bootstrap_trace_data():
"""Test bootstrap_trace_data ... | 181 | 6,838 |
dspy | tests/teleprompt/test_gepa.py | .py | import json
import threading
from typing import Any
from unittest import mock
import pytest
import dspy
import dspy.clients
from dspy import Example
from dspy.predict import Predict
from dspy.teleprompt.gepa import instruction_proposal
from dspy.utils.dummies import DummyLM
class SimpleModule(dspy.Module):
def ... | 635 | 34,678 |
dspy | tests/teleprompt/test_bootstrap.py | .py | import pytest
import dspy
from dspy import Example
from dspy.predict import Predict
from dspy.teleprompt import BootstrapFewShot
from dspy.utils.dummies import DummyLM
# Define a simple metric function for testing
def simple_metric(example, prediction, trace=None):
# Simplified metric for testing: true if predic... | 135 | 5,010 |
dspy | tests/teleprompt/test_teleprompt.py | .py | from dspy.teleprompt.teleprompt import Teleprompter
class DummyTeleprompter(Teleprompter):
def __init__(self, param1: int, param2: str):
super().__init__()
self.param1 = param1
self.param2 = param2
def compile(self, student, *, trainset, teacher=None, valset=None, **kwargs):
r... | 18 | 513 |
dspy | tests/teleprompt/test_random_search.py | .py | import pytest
import dspy
from dspy import Example
from dspy.predict import Predict
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
from dspy.utils.dummies import DummyLM
class SimpleModule(dspy.Module):
def __init__(self, signature):
super().__init__()
self.predictor = Predict(signa... | 77 | 2,785 |
dspy | tests/teleprompt/test_ensemble.py | .py | import pytest
import dspy
from dspy.teleprompt import Ensemble
class MockProgram(dspy.Module):
def __init__(self, output):
super().__init__()
self.output = output
def forward(self, *args, **kwargs):
return self.output
# Simple reduction function to test with
def mock_reduce_fn(outp... | 60 | 1,910 |
dspy | tests/teleprompt/test_utils.py | .py | from unittest.mock import Mock, patch
import dspy
from dspy.teleprompt.utils import create_n_fewshot_demo_sets, eval_candidate_program
from dspy.utils.dummies import DummyLM
class DummyModule(dspy.Module):
def __init__(self):
super().__init__()
def forward(self, **kwargs):
pass
def test_ev... | 98 | 3,368 |
dspy | tests/callback/test_callback.py | .py | import asyncio
import time
import cloudpickle
import pytest
import dspy
from dspy.utils.callback import ACTIVE_CALL_ID, BaseCallback, with_callbacks
from dspy.utils.callback_context import _bind_active_call_id
from dspy.utils.dummies import DummyLM
@pytest.fixture(autouse=True)
def reset_settings():
# Make sure... | 373 | 11,344 |
dspy | tests/callback/test_interpreter_callback.py | .py | import json
import pytest
import dspy
from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreterError, FinalOutput
from dspy.utils.callback import ACTIVE_CALL_ID, BaseCallback, with_callbacks
class RecordingCallback(BaseCallback):
def __init__(self, name=None, observed=None):
self.... | 265 | 9,979 |
dspy | tests/callback/test_optimizer_callback.py | .py | import asyncio
from unittest.mock import Mock, patch
import cloudpickle
import pytest
import dspy
from dspy.teleprompt.bettertogether import BetterTogether
from dspy.teleprompt.teleprompt import Teleprompter
from dspy.teleprompt.vanilla import LabeledFewShot
from dspy.utils.callback import ACTIVE_CALL_ID, BaseCallbac... | 351 | 12,725 |
dspy | tests/metadata/test_metadata.py | .py | import re
import dspy
def test_metadata():
assert dspy.__name__ == "dspy"
assert re.match(r"\d+\.\d+\.\d+", dspy.__version__)
assert dspy.__author__ == "Omar Khattab"
assert dspy.__author_email__ == "okhattab@stanford.edu"
assert dspy.__url__ == "https://github.com/stanfordnlp/dspy"
assert ds... | 13 | 349 |
dspy | tests/clients/test_embedding.py | .py | from unittest.mock import MagicMock, patch
import numpy as np
import pytest
import dspy
from dspy.clients.embedding import Embedder
# Mock response format similar to litellm's embedding response.
class MockEmbeddingResponse:
def __init__(self, embeddings):
self.data = [{"embedding": emb} for emb in embe... | 200 | 6,630 |
dspy | tests/clients/test_lazy_litellm_import.py | .py | import importlib.util
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
import pytest
def _hide_litellm(monkeypatch):
real_find_spec = importlib.util.find_spec
def find_spec(name, *args, **kwargs):
if name == "litellm" or name.startswith("litellm."):
return No... | 87 | 2,388 |
dspy | tests/clients/test_databricks.py | .py | """Test the Databricks finetuning and deployment.
This test requires valid Databricks credentials, so it is skipped on github actions. Right now it is only used for
manual testing.
"""
import pytest
import dspy
from dspy.clients.databricks import (
DatabricksProvider,
TrainingJobDatabricks,
_create_direc... | 95 | 2,984 |
dspy | tests/clients/test_lm_direct_live.py | .py | """Live coverage for the experimental direct LM call interface.
These tests exercise provider behavior that cannot be verified with the mocked unit tests in `test_lm.py`: typed
message turns, tool-call transcripts, and reusing an `LMResponse` as an assistant turn across chat and Responses API
providers.
They are inte... | 483 | 15,782 |
dspy | tests/clients/test_lm_local.py | .py | from unittest import mock
from unittest.mock import patch
from dspy.clients.lm_local import LocalProvider
@patch("dspy.clients.lm_local.threading.Thread")
@patch("dspy.clients.lm_local.subprocess.Popen")
@patch("dspy.clients.lm_local.get_free_port")
@patch("dspy.clients.lm_local.wait_for_server")
def test_command_wi... | 98 | 3,438 |
dspy | tests/clients/test_lm.py | .py | import json
import tempfile
import warnings
from pathlib import Path
from unittest import mock
from unittest.mock import patch
import litellm
import pydantic
import pytest
import tenacity
from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
from litellm.utils import Choices, Message, ModelRespo... | 2,175 | 76,638 |
dspy | tests/clients/test_disk_serialization.py | .py | """Tests for restricted pickle deserialization."""
import io
import pickle
import subprocess
import sys
from dataclasses import dataclass
import diskcache
import numpy as np
import pydantic
import pytest
from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
from litellm.types.utils import Embed... | 405 | 13,432 |
dspy | tests/clients/test_inspect_global_history.py | .py | from io import StringIO
import pytest
import dspy
from dspy.clients.base_lm import GLOBAL_HISTORY
from dspy.utils.dummies import DummyLM
from dspy.utils.inspect_history import pretty_print_history
@pytest.fixture(autouse=True)
def clear_history():
GLOBAL_HISTORY.clear()
yield
def test_inspect_history_basi... | 140 | 4,051 |
dspy | tests/clients/test_cache.py | .py | import os
from dataclasses import dataclass
from unittest.mock import patch
import pydantic
import pytest
from cachetools import LRUCache
from diskcache import FanoutCache
import dspy
from dspy.clients.cache import Cache
@dataclass
class DummyResponse:
message: str
usage: dict
@dataclass
class CacheValida... | 557 | 18,331 |
dspy | tests/retrievers/test_colbertv2.py | .py | from unittest.mock import MagicMock, patch
import pytest
from dspy.dsp.colbertv2 import colbertv2_get_request_v2, colbertv2_post_request_v2
def test_get_request_raises_on_server_error():
mock_response = MagicMock()
mock_response.json.return_value = {"error": True, "message": "connection failed"}
with p... | 42 | 1,588 |
dspy | tests/retrievers/test_embeddings.py | .py | import os
import tempfile
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import pytest
from dspy.retrievers.embeddings import Embeddings, EmbeddingsWithScores
def dummy_corpus():
return [
"The cat sat on the mat.",
"The dog barked at the mailman.",
"Birds fly in the... | 170 | 5,734 |
dspy | tests/datasets/test_dataset.py | .py | import tempfile
import uuid
import pytest
from dspy import Example
from dspy.datasets.dataset import Dataset
dummy_data = """content,question,answer
"This is content 1","What is this?","This is answer 1"
"This is content 2","What is that?","This is answer 2"
"""
class CSVDataset(Dataset):
def __init__(self, fi... | 75 | 2,347 |
dspy | tests/docs/test_mkdocs_links.py | .py | import os
def test_nav_files_exist():
# Read mkdocs.yml
docs_dir = os.path.join(os.path.dirname(__file__), "..", "..", "docs", "docs")
yaml_path = os.path.join(os.path.dirname(__file__), "..", "..", "docs", "mkdocs.yml")
# Read file and extract nav section
with open(yaml_path) as f:
conte... | 39 | 1,241 |
dspy | tests/test_utils/server/__init__.py | .py | import json
import os
import socket
import subprocess
import sys
import tempfile
import time
from collections.abc import Iterator
from typing import Any
import pytest
from tests.test_utils.server.litellm_server import LITELLM_TEST_SERVER_LOG_FILE_PATH_ENV_VAR
@pytest.fixture()
def litellm_test_server(_litellm_test_... | 100 | 3,421 |
dspy | tests/test_utils/server/litellm_server.py | .py | import json
import os
from typing import AsyncIterator, Iterator
import litellm
from litellm import CustomLLM
from litellm.types.utils import GenericStreamingChunk
LITELLM_TEST_SERVER_LOG_FILE_PATH_ENV_VAR = "LITELLM_TEST_SERVER_LOG_FILE_PATH"
class DSPyTestModel(CustomLLM):
def completion(self, *args, **kwargs... | 90 | 3,302 |
dspy | tests/core/test_types.py | .py | import json
import pydantic
import pytest
from dspy.core.types import (
LMAudioPart,
LMBinaryPart,
LMConfig,
LMDocumentPart,
LMHistoryEntry,
LMImagePart,
LMMessage,
LMOutput,
LMOutputBuilder,
LMPromptCacheConfig,
LMReasoningConfig,
LMRequest,
LMRequestPatch,
LMR... | 497 | 16,224 |
dspy | tests/predict/test_chain_of_thought.py | .py | from unittest import mock
import pytest
from litellm.utils import Choices, Message, ModelResponse
import dspy
from dspy import ChainOfThought
from dspy.utils import DummyLM
def test_initialization_with_string_signature():
lm = DummyLM([{"reasoning": "find the number after 1", "answer": "2"}])
dspy.configure... | 86 | 3,157 |
dspy | tests/predict/test_program_of_thought.py | .py | import threading
from unittest.mock import Mock, patch
import pytest
import dspy
from dspy import ProgramOfThought, Signature
from dspy.evaluate.metrics import answer_exact_match
from dspy.primitives.code_interpreter import CodeInterpreterError, FinalOutput
from dspy.primitives.python_interpreter import PythonInterpr... | 274 | 9,470 |
dspy | tests/predict/test_react.py | .py | import re
import pytest
from pydantic import BaseModel
import dspy
import dspy.adapters.base as adapter_base
import dspy.adapters.utils as adapter_utils
from dspy.utils.dummies import DummyLM
from dspy.utils.exceptions import ContextWindowExceededError
@pytest.mark.extra
def test_tool_observation_preserves_custom_t... | 537 | 19,563 |
dspy | tests/predict/test_parallel.py | .py | import threading
import dspy
from dspy.utils.callback import ACTIVE_CALL_ID, BaseCallback
from dspy.utils.dummies import DummyLM
def test_parallel_module():
lm = DummyLM(
[
{"output": "test output 1"},
{"output": "test output 2"},
{"output": "test output 3"},
... | 262 | 8,462 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.