mcy98's picture
Upload folder using huggingface_hub
e89a301 verified
Raw History Blame Contribute Delete
8.54 kB
import unittest
import numpy as np
import pandas as pd
from unittest.mock import patch
# Import canonical and generated functions
from models.canonical import (
get_scaler as canonical_get_scaler,
truncate_input as canonical_truncate_input,
handle_prediction as canonical_handle_prediction,
generate_predictions as canonical_generate_predictions,
get_llmtime_predictions_data as canonical_get_llmtime_predictions_data,
Scaler as CanonicalScaler
)
from models.llmtime import (
get_scaler as generated_get_scaler,
truncate_input as generated_truncate_input,
handle_prediction as generated_handle_prediction,
generate_predictions as generated_generate_predictions,
get_llmtime_predictions_data as generated_get_llmtime_predictions_data,
Scaler as GeneratedScaler
)
# Mocks for external dependencies
class DummySettings:
"""
FIX: Set `signed=True` and `plus_sign=""` to work around a bug in the
deserialize_str function, which fails to set a sign for unsigned numbers.
"""
def __init__(self, time_sep=",", base=10, prec=4, half_bin_correction=True, max_val=1000.0,
signed=True, minus_sign="-", plus_sign="", decimal_point=".", bit_sep="", fixed_length=False):
self.time_sep = time_sep
self.base = base
self.prec = prec
self.half_bin_correction = half_bin_correction
self.max_val = max_val
self.signed = signed
self.minus_sign = minus_sign
self.plus_sign = plus_sign
self.decimal_point = decimal_point
self.bit_sep = bit_sep
self.fixed_length = fixed_length
class TestLLMTimeForecasting(unittest.TestCase):
def setUp(self):
# Example time series
self.history = np.array([1.0, 2.0, 3.0, np.nan, 4.0, 5.0])
self.history_no_nan = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
self.input_arr = np.array([10.0, 11.0, 12.0, 13.0])
self.input_str = "10.0,11.0,12.0,13.0,"
self.settings = DummySettings(time_sep=",")
self.model = "dummy_model"
self.steps = 2
def test_get_scaler_equivalence(self):
# Test both basic and shifted scaling
for basic in [True, False]:
can_scaler = canonical_get_scaler(self.history, basic=basic)
gen_scaler = generated_get_scaler(self.history, basic=basic)
# Test both transform and inv_transform on some value(s)
values = np.array([2.0, 4.0, 5.0])
np.testing.assert_allclose(
can_scaler.transform(values), gen_scaler.transform(values), rtol=1e-8
)
np.testing.assert_allclose(
can_scaler.inv_transform(values), gen_scaler.inv_transform(values), rtol=1e-8
)
def test_truncate_input_equivalence(self):
# We need to mock the tokenization functions for this test
with patch('models.llms.tokenization_fns', {self.model: lambda s: s.split(",")}), \
patch('models.llms.context_lengths', {self.model: 10}):
can_arr, can_str = canonical_truncate_input(self.input_arr, self.input_str, self.settings, self.model, self.steps)
gen_arr, gen_str = generated_truncate_input(self.input_arr, self.input_str, self.settings, self.model, self.steps)
np.testing.assert_array_equal(can_arr, gen_arr)
self.assertEqual(can_str, gen_str)
def test_handle_prediction_equivalence(self):
arr = np.array([1.0, 2.0])
# Output shorter than expected_length (tests padding)
can = canonical_handle_prediction(arr, 4, strict=False)
gen = generated_handle_prediction(arr, 4, strict=False)
np.testing.assert_allclose(can, gen, rtol=1e-8)
# Output longer than expected_length (tests truncation)
arr2 = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
can = canonical_handle_prediction(arr2, 3, strict=False)
gen = generated_handle_prediction(arr2, 3, strict=False)
np.testing.assert_allclose(can, gen, rtol=1e-8)
# Output None (input None)
can = canonical_handle_prediction(None, 3, strict=False)
gen = generated_handle_prediction(None, 3, strict=False)
self.assertEqual(can, gen)
def test_generate_predictions_equivalence(self):
# Dummy completion_fn always returns same deterministic prediction
def dummy_completion_fn(input_str, steps, settings, num_samples=1, temp=0.7):
return ["1.0,2.0"] * num_samples
# Scalers (identity)
scalers = [CanonicalScaler(transform=lambda x: x, inv_transform=lambda x: x) for _ in range(2)]
gen_scalers = [GeneratedScaler(transform=lambda x: x, inv_transform=lambda x: x) for _ in range(2)]
input_strs = ["1.0,2.0,", "3.0,4.0,"]
steps = 2
can = canonical_generate_predictions(dummy_completion_fn, input_strs, steps, self.settings, scalers)
gen = generated_generate_predictions(dummy_completion_fn, input_strs, steps, self.settings, gen_scalers)
# Compare predictions (first output)
for c_arr, g_arr in zip(can[0], gen[0]):
for c_row, g_row in zip(c_arr, g_arr):
np.testing.assert_allclose(
np.array(c_row), np.array(g_row), rtol=1e-8
)
# Completions (second output)
self.assertEqual(can[1], gen[1])
# Input strings (third output)
self.assertEqual(can[2], gen[2])
def test_get_llmtime_predictions_data_equivalence(self):
# Setup a tiny forecast with deterministic dummy LLM completion
train = [np.array([1.0, 2.0, 3.0]), np.array([4.0, 5.0, 6.0])]
test = [np.array([7.0, 8.0]), np.array([9.0, 10.0])]
steps = 2
# Define a deterministic mock completion function
def deterministic_completion_fn(input_str, **kwargs):
if '3.0' in input_str:
return ["7.0,8.0"]
elif '6.0' in input_str:
return ["9.0,10.0"]
return ["0.0,0.0"]
# Define the mock registries to be patched in
mock_completion_fns = {"dummy_model": deterministic_completion_fn}
mock_nll_fns = {"dummy_model": lambda **kwargs: 0.0}
mock_tokenization_fns = {"dummy_model": lambda s: s.split(",")}
mock_context_lengths = {"dummy_model": 10}
# Use patch to reliably mock the dependencies for both canonical and generated functions.
with patch('models.canonical.completion_fns', mock_completion_fns), \
patch('models.canonical.nll_fns', mock_nll_fns), \
patch('models.canonical.tokenization_fns', mock_tokenization_fns), \
patch('models.canonical.context_lengths', mock_context_lengths), \
patch('models.llmtime.completion_fns', mock_completion_fns), \
patch('models.llmtime.nll_fns', mock_nll_fns), \
patch('models.llmtime.tokenization_fns', mock_tokenization_fns), \
patch('models.llmtime.context_lengths', mock_context_lengths):
settings = DummySettings(time_sep=",")
can_out = canonical_get_llmtime_predictions_data(
train, test, "dummy_model", settings, num_samples=1, temp=0.7
)
gen_out = generated_get_llmtime_predictions_data(
train, test, "dummy_model", settings, num_samples=1, temp=0.7
)
# Compare structure and all major fields
self.assertEqual(list(can_out.keys()), list(gen_out.keys()))
# Compare DataFrame outputs (samples, medians)
if isinstance(can_out["samples"], pd.DataFrame):
pd.testing.assert_frame_equal(can_out["samples"], gen_out["samples"])
pd.testing.assert_series_equal(can_out["median"], gen_out["median"])
elif isinstance(can_out["samples"], list):
for cdf, gdf in zip(can_out["samples"], gen_out["samples"]):
pd.testing.assert_frame_equal(cdf, gdf)
for cs, gs in zip(can_out["median"], gen_out["median"]):
pd.testing.assert_series_equal(cs, gs)
# Compare info, completions_list, input_strs, NLL/D if present
self.assertEqual(can_out["info"], gen_out["info"])
self.assertEqual(can_out["completions_list"], gen_out["completions_list"])
self.assertEqual(can_out["input_strs"], gen_out["input_strs"])
if "NLL/D" in can_out:
self.assertAlmostEqual(can_out["NLL/D"], gen_out["NLL/D"], places=8)
if __name__ == "__main__":
unittest.main()