TabQueryBench commited on
Commit
5f6fc33
·
verified ·
1 Parent(s): 40b3396

Resume SynthData0523 main/c19 batch 5

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +33 -0
  2. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/env.py +39 -0
  3. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/metrics.py +157 -0
  4. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/util.py +347 -0
  5. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/real.csv +3 -0
  6. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/test.csv +3 -0
  7. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/val.csv +3 -0
  8. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/conftest.py +193 -0
  9. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_attention.py +51 -0
  10. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_config.py +62 -0
  11. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_flow_model.py +219 -0
  12. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_mlp.py +85 -0
  13. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_reconstructor.py +51 -0
  14. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_tokenizer.py +85 -0
  15. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_trainer.py +98 -0
  16. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_transformer.py +73 -0
  17. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_unimodmlp.py +72 -0
  18. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_utils.py +49 -0
  19. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/utils_train.py +183 -0
  20. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_tabbyflow_gen.py +43 -0
  21. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_tabbyflow_train.py +33 -0
  22. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/gen_20260510_210653.log +3 -0
  23. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/input_snapshot.json +3 -0
  24. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/models_tabbyflow/trained.pt +3 -0
  25. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/normalized_schema_snapshot.json +3 -0
  26. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/public_gate_report.json +3 -0
  27. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/staged_input_manifest.json +3 -0
  28. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/run_config.json +3 -0
  29. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/runtime_result.json +3 -0
  30. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/staged_features.json +3 -0
  31. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/test.csv +3 -0
  32. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/train.csv +3 -0
  33. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/val.csv +3 -0
  34. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_report.json +3 -0
  35. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_transforms_applied.json +3 -0
  36. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/model_input_manifest.json +3 -0
  37. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow-c19-32759-20260510_210653.csv +3 -0
  38. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow_train_meta.json +3 -0
  39. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_test.npy +3 -0
  40. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_train.npy +3 -0
  41. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_val.npy +3 -0
  42. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_test.npy +3 -0
  43. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_train.npy +3 -0
  44. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_val.npy +3 -0
  45. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/info.json +3 -0
  46. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/real.csv +3 -0
  47. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/staged_features.json +3 -0
  48. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/test.csv +3 -0
  49. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/train.csv +3 -0
  50. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/val.csv +3 -0
.gitattributes CHANGED
@@ -2819,3 +2819,36 @@ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef
2819
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/shapes.csv filter=lfs diff=lfs merge=lfs -text
2820
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/trends.csv filter=lfs diff=lfs merge=lfs -text
2821
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/pyproject.toml filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2819
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/shapes.csv filter=lfs diff=lfs merge=lfs -text
2820
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/trends.csv filter=lfs diff=lfs merge=lfs -text
2821
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/pyproject.toml filter=lfs diff=lfs merge=lfs -text
2822
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text
2823
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text
2824
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2825
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/gen_20260510_210653.log filter=lfs diff=lfs merge=lfs -text
2826
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
2827
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/models_tabbyflow/trained.pt filter=lfs diff=lfs merge=lfs -text
2828
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
2829
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
2830
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
2831
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/run_config.json filter=lfs diff=lfs merge=lfs -text
2832
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/runtime_result.json filter=lfs diff=lfs merge=lfs -text
2833
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
2834
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
2835
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
2836
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
2837
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_report.json filter=lfs diff=lfs merge=lfs -text
2838
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
2839
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
2840
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow-c19-32759-20260510_210653.csv filter=lfs diff=lfs merge=lfs -text
2841
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow_train_meta.json filter=lfs diff=lfs merge=lfs -text
2842
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_test.npy filter=lfs diff=lfs merge=lfs -text
2843
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_train.npy filter=lfs diff=lfs merge=lfs -text
2844
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_val.npy filter=lfs diff=lfs merge=lfs -text
2845
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
2846
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
2847
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
2848
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/info.json filter=lfs diff=lfs merge=lfs -text
2849
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text
2850
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/staged_features.json filter=lfs diff=lfs merge=lfs -text
2851
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text
2852
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text
2853
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2854
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/env.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Have not used in TabDDPM project.
3
+ """
4
+
5
+ import datetime
6
+ import os
7
+ import shutil
8
+ import typing as ty
9
+ from pathlib import Path
10
+
11
+ PROJ = Path('tab-ddpm/').absolute().resolve()
12
+ EXP = PROJ / 'exp'
13
+ DATA = PROJ / 'data'
14
+
15
+
16
+ def get_path(path: ty.Union[str, Path]) -> Path:
17
+ if isinstance(path, str):
18
+ path = Path(path)
19
+ if not path.is_absolute():
20
+ path = PROJ / path
21
+ return path.resolve()
22
+
23
+
24
+ def get_relative_path(path: ty.Union[str, Path]) -> Path:
25
+ return get_path(path).relative_to(PROJ)
26
+
27
+
28
+ def duplicate_path(
29
+ src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
30
+ ) -> None:
31
+ src = get_path(src)
32
+ alternative_project_dir = get_path(alternative_project_dir)
33
+ dst = alternative_project_dir / src.relative_to(PROJ)
34
+ dst.parent.mkdir(parents=True, exist_ok=True)
35
+ if dst.exists():
36
+ dst = dst.with_name(
37
+ dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
38
+ )
39
+ (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/metrics.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import Any, Optional, Tuple, Dict, Union, cast
3
+ from functools import partial
4
+
5
+ import numpy as np
6
+ import scipy.special
7
+ import sklearn.metrics as skm
8
+
9
+ from . import util
10
+ from .util import TaskType
11
+
12
+
13
+ class PredictionType(enum.Enum):
14
+ LOGITS = 'logits'
15
+ PROBS = 'probs'
16
+
17
+ class MetricsReport:
18
+ def __init__(self, report: dict, task_type: TaskType):
19
+ self._res = {k: {} for k in report.keys()}
20
+ if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
21
+ self._metrics_names = ["acc", "f1"]
22
+ for k in report.keys():
23
+ self._res[k]["acc"] = report[k]["accuracy"]
24
+ self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
25
+ if task_type == TaskType.BINCLASS:
26
+ self._res[k]["roc_auc"] = report[k]["roc_auc"]
27
+ self._metrics_names.append("roc_auc")
28
+
29
+ elif task_type == TaskType.REGRESSION:
30
+ self._metrics_names = ["r2", "rmse"]
31
+ for k in report.keys():
32
+ self._res[k]["r2"] = report[k]["r2"]
33
+ self._res[k]["rmse"] = report[k]["rmse"]
34
+ else:
35
+ raise "Unknown TaskType!"
36
+
37
+ def get_splits_names(self) -> list[str]:
38
+ return self._res.keys()
39
+
40
+ def get_metrics_names(self) -> list[str]:
41
+ return self._metrics_names
42
+
43
+ def get_metric(self, split: str, metric: str) -> float:
44
+ return self._res[split][metric]
45
+
46
+ def get_val_score(self) -> float:
47
+ return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
48
+
49
+ def get_test_score(self) -> float:
50
+ return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
51
+
52
+ def print_metrics(self) -> None:
53
+ res = {
54
+ "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
55
+ "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
56
+ }
57
+
58
+ print("*"*100)
59
+ print("[val]")
60
+ print(res["val"])
61
+ print("[test]")
62
+ print(res["test"])
63
+
64
+ return res
65
+
66
+ class SeedsMetricsReport:
67
+ def __init__(self):
68
+ self._reports = []
69
+
70
+ def add_report(self, report: MetricsReport) -> None:
71
+ self._reports.append(report)
72
+
73
+ def get_mean_std(self) -> dict:
74
+ res = {k: {} for k in ["train", "val", "test"]}
75
+ for split in self._reports[0].get_splits_names():
76
+ for metric in self._reports[0].get_metrics_names():
77
+ res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
78
+
79
+ agg_res = {k: {} for k in ["train", "val", "test"]}
80
+ for split in self._reports[0].get_splits_names():
81
+ for metric in self._reports[0].get_metrics_names():
82
+ for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
83
+ agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
84
+ self._res = res
85
+ self._agg_res = agg_res
86
+
87
+ return agg_res
88
+
89
+ def print_result(self) -> dict:
90
+ res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
91
+ print("="*100)
92
+ print("EVAL RESULTS:")
93
+ print("[val]")
94
+ print(res["val"])
95
+ print("[test]")
96
+ print(res["test"])
97
+ print("="*100)
98
+ return res
99
+
100
+ def calculate_rmse(
101
+ y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float:
102
+ rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
103
+ if std is not None:
104
+ rmse *= std
105
+ return rmse
106
+
107
+
108
+ def _get_labels_and_probs(
109
+ y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
110
+ ) -> Tuple[np.ndarray, Optional[np.ndarray]]:
111
+ assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
112
+
113
+ if prediction_type is None:
114
+ return y_pred, None
115
+
116
+ if prediction_type == PredictionType.LOGITS:
117
+ probs = (
118
+ scipy.special.expit(y_pred)
119
+ if task_type == TaskType.BINCLASS
120
+ else scipy.special.softmax(y_pred, axis=1)
121
+ )
122
+ elif prediction_type == PredictionType.PROBS:
123
+ probs = y_pred
124
+ else:
125
+ util.raise_unknown('prediction_type', prediction_type)
126
+
127
+ assert probs is not None
128
+ labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
129
+ return labels.astype('int64'), probs
130
+
131
+
132
+ def calculate_metrics(
133
+ y_true: np.ndarray,
134
+ y_pred: np.ndarray,
135
+ task_type: Union[str, TaskType],
136
+ prediction_type: Optional[Union[str, PredictionType]],
137
+ y_info: Dict[str, Any],
138
+ ) -> Dict[str, Any]:
139
+ # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
140
+ task_type = TaskType(task_type)
141
+ if prediction_type is not None:
142
+ prediction_type = PredictionType(prediction_type)
143
+
144
+ if task_type == TaskType.REGRESSION:
145
+ assert prediction_type is None
146
+ assert 'std' in y_info
147
+ rmse = calculate_rmse(y_true, y_pred, y_info['std'])
148
+ r2 = skm.r2_score(y_true, y_pred)
149
+ result = {'rmse': rmse, 'r2': r2}
150
+ else:
151
+ labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
152
+ result = cast(
153
+ Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
154
+ )
155
+ if task_type == TaskType.BINCLASS:
156
+ result['roc_auc'] = skm.roc_auc_score(y_true, probs)
157
+ return result
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/util.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import atexit
3
+ import enum
4
+ import json
5
+ import os
6
+ import pickle
7
+ import shutil
8
+ import sys
9
+ import time
10
+ import uuid
11
+ from copy import deepcopy
12
+ from dataclasses import asdict, fields, is_dataclass
13
+ from pathlib import Path
14
+ from pprint import pprint
15
+ from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
16
+
17
+ import __main__
18
+ import numpy as np
19
+ import tomli
20
+ import tomli_w
21
+ import torch
22
+ import typing as ty
23
+
24
+ from . import env
25
+
26
+ RawConfig = Dict[str, Any]
27
+ Report = Dict[str, Any]
28
+ T = TypeVar('T')
29
+
30
+
31
+ class Part(enum.Enum):
32
+ TRAIN = 'train'
33
+ VAL = 'val'
34
+ TEST = 'test'
35
+
36
+ def __str__(self) -> str:
37
+ return self.value
38
+
39
+
40
+ class TaskType(enum.Enum):
41
+ BINCLASS = 'binclass'
42
+ MULTICLASS = 'multiclass'
43
+ REGRESSION = 'regression'
44
+
45
+ def __str__(self) -> str:
46
+ return self.value
47
+
48
+
49
+
50
+ def update_training_log(training_log, data, metrics):
51
+ def _update(log_part, data_part):
52
+ for k, v in data_part.items():
53
+ if isinstance(v, dict):
54
+ _update(log_part.setdefault(k, {}), v)
55
+ elif isinstance(v, list):
56
+ log_part.setdefault(k, []).extend(v)
57
+ else:
58
+ log_part.setdefault(k, []).append(v)
59
+
60
+ _update(training_log, data)
61
+ transposed_metrics = {}
62
+ for part, part_metrics in metrics.items():
63
+ for metric_name, value in part_metrics.items():
64
+ transposed_metrics.setdefault(metric_name, {})[part] = value
65
+ _update(training_log, transposed_metrics)
66
+
67
+
68
+ def raise_unknown(unknown_what: str, unknown_value: Any):
69
+ raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
70
+
71
+
72
+ def _replace(data, condition, value):
73
+ def do(x):
74
+ if isinstance(x, dict):
75
+ return {k: do(v) for k, v in x.items()}
76
+ elif isinstance(x, list):
77
+ return [do(y) for y in x]
78
+ else:
79
+ return value if condition(x) else x
80
+
81
+ return do(data)
82
+
83
+
84
+ _CONFIG_NONE = '__none__'
85
+
86
+
87
+ def unpack_config(config: RawConfig) -> RawConfig:
88
+ config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
89
+ return config
90
+
91
+
92
+ def pack_config(config: RawConfig) -> RawConfig:
93
+ config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
94
+ return config
95
+
96
+
97
+ def load_config(path: Union[Path, str]) -> Any:
98
+ with open(path, 'rb') as f:
99
+ return unpack_config(tomli.load(f))
100
+
101
+
102
+ def dump_config(config: Any, path: Union[Path, str]) -> None:
103
+ with open(path, 'wb') as f:
104
+ tomli_w.dump(pack_config(config), f)
105
+ # check that there are no bugs in all these "pack/unpack" things
106
+ assert config == load_config(path)
107
+
108
+
109
+ def load_json(path: Union[Path, str], **kwargs) -> Any:
110
+ return json.loads(Path(path).read_text(), **kwargs)
111
+
112
+
113
+ def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
114
+ kwargs.setdefault('indent', 4)
115
+ Path(path).write_text(json.dumps(x, **kwargs) + '\n')
116
+
117
+
118
+ def load_pickle(path: Union[Path, str], **kwargs) -> Any:
119
+ return pickle.loads(Path(path).read_bytes(), **kwargs)
120
+
121
+
122
+ def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
123
+ Path(path).write_bytes(pickle.dumps(x, **kwargs))
124
+
125
+
126
+ def load(path: Union[Path, str], **kwargs) -> Any:
127
+ return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
128
+
129
+
130
+ def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
131
+ return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
132
+
133
+
134
+ def _get_output_item_path(
135
+ path: Union[str, Path], filename: str, must_exist: bool
136
+ ) -> Path:
137
+ path = env.get_path(path)
138
+ if path.suffix == '.toml':
139
+ path = path.with_suffix('')
140
+ if path.is_dir():
141
+ path = path / filename
142
+ else:
143
+ assert path.name == filename
144
+ assert path.parent.exists()
145
+ if must_exist:
146
+ assert path.exists()
147
+ return path
148
+
149
+
150
+ def load_report(path: Path) -> Report:
151
+ return load_json(_get_output_item_path(path, 'report.json', True))
152
+
153
+
154
+ def dump_report(report: dict, path: Path) -> None:
155
+ dump_json(report, _get_output_item_path(path, 'report.json', False))
156
+
157
+
158
+ def load_predictions(path: Path) -> Dict[str, np.ndarray]:
159
+ with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
160
+ return {x: predictions[x] for x in predictions}
161
+
162
+
163
+ def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
164
+ np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
165
+
166
+
167
+ def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
168
+ dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
169
+
170
+
171
+ def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
172
+ return torch.load(
173
+ _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
174
+ )
175
+
176
+
177
+ def get_device() -> torch.device:
178
+ if torch.cuda.is_available():
179
+ assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
180
+ return torch.device('cuda:0')
181
+ else:
182
+ return torch.device('cpu')
183
+
184
+
185
+ def _print_sep(c, size=100):
186
+ print(c * size)
187
+
188
+
189
+ _LAST_SNAPSHOT_TIME = None
190
+
191
+
192
+ def backup_output(output_dir: Path) -> None:
193
+ backup_dir = os.environ.get('TMP_OUTPUT_PATH')
194
+ snapshot_dir = os.environ.get('SNAPSHOT_PATH')
195
+ if backup_dir is None:
196
+ assert snapshot_dir is None
197
+ return
198
+ assert snapshot_dir is not None
199
+
200
+ try:
201
+ relative_output_dir = output_dir.relative_to(env.PROJ)
202
+ except ValueError:
203
+ return
204
+
205
+ for dir_ in [backup_dir, snapshot_dir]:
206
+ new_output_dir = dir_ / relative_output_dir
207
+ prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
208
+ new_output_dir.parent.mkdir(exist_ok=True, parents=True)
209
+ if new_output_dir.exists():
210
+ new_output_dir.rename(prev_backup_output_dir)
211
+ shutil.copytree(output_dir, new_output_dir)
212
+ # the case for evaluate.py which automatically creates configs
213
+ if output_dir.with_suffix('.toml').exists():
214
+ shutil.copyfile(
215
+ output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
216
+ )
217
+ if prev_backup_output_dir.exists():
218
+ shutil.rmtree(prev_backup_output_dir)
219
+
220
+ global _LAST_SNAPSHOT_TIME
221
+ if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
222
+ import nirvana_dl.snapshot # type: ignore[code]
223
+
224
+ nirvana_dl.snapshot.dump_snapshot()
225
+ _LAST_SNAPSHOT_TIME = time.time()
226
+ print('The snapshot was saved!')
227
+
228
+
229
+ def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
230
+ return (
231
+ {k: v['score'] for k, v in metrics.items()}
232
+ if 'score' in next(iter(metrics.values()))
233
+ else None
234
+ )
235
+
236
+
237
+ def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
238
+ return ' '.join(
239
+ f"[{x}] {metrics[x]['score']:.3f}"
240
+ for x in ['test', 'val', 'train']
241
+ if x in metrics
242
+ )
243
+
244
+
245
+ def finish(output_dir: Path, report: dict) -> None:
246
+ print()
247
+ _print_sep('=')
248
+
249
+ metrics = report.get('metrics')
250
+ if metrics is not None:
251
+ scores = _get_scores(metrics)
252
+ if scores is not None:
253
+ dump_json(scores, output_dir / 'scores.json')
254
+ print(format_scores(metrics))
255
+ _print_sep('-')
256
+
257
+ dump_report(report, output_dir)
258
+ json_output_path = os.environ.get('JSON_OUTPUT_FILE')
259
+ if json_output_path:
260
+ try:
261
+ key = str(output_dir.relative_to(env.PROJ))
262
+ except ValueError:
263
+ pass
264
+ else:
265
+ json_output_path = Path(json_output_path)
266
+ try:
267
+ json_data = json.loads(json_output_path.read_text())
268
+ except (FileNotFoundError, json.decoder.JSONDecodeError):
269
+ json_data = {}
270
+ json_data[key] = load_json(output_dir / 'report.json')
271
+ json_output_path.write_text(json.dumps(json_data, indent=4))
272
+ shutil.copyfile(
273
+ json_output_path,
274
+ os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
275
+ )
276
+
277
+ output_dir.joinpath('DONE').touch()
278
+ backup_output(output_dir)
279
+ print(f'Done! | {report.get("time")} | {output_dir}')
280
+ _print_sep('=')
281
+ print()
282
+
283
+
284
+ def from_dict(datacls: Type[T], data: dict) -> T:
285
+ assert is_dataclass(datacls)
286
+ data = deepcopy(data)
287
+ for field in fields(datacls):
288
+ if field.name not in data:
289
+ continue
290
+ if is_dataclass(field.type):
291
+ data[field.name] = from_dict(field.type, data[field.name])
292
+ elif (
293
+ get_origin(field.type) is Union
294
+ and len(get_args(field.type)) == 2
295
+ and get_args(field.type)[1] is type(None)
296
+ and is_dataclass(get_args(field.type)[0])
297
+ ):
298
+ if data[field.name] is not None:
299
+ data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
300
+ return datacls(**data)
301
+
302
+
303
+ def replace_factor_with_value(
304
+ config: RawConfig,
305
+ key: str,
306
+ reference_value: int,
307
+ bounds: Tuple[float, float],
308
+ ) -> None:
309
+ factor_key = key + '_factor'
310
+ if factor_key not in config:
311
+ assert key in config
312
+ else:
313
+ assert key not in config
314
+ factor = config.pop(factor_key)
315
+ assert bounds[0] <= factor <= bounds[1]
316
+ config[key] = int(factor * reference_value)
317
+
318
+
319
+ def get_temporary_copy(path: Union[str, Path]) -> Path:
320
+ path = env.get_path(path)
321
+ assert not path.is_dir() and not path.is_symlink()
322
+ tmp_path = path.with_name(
323
+ path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
324
+ )
325
+ shutil.copyfile(path, tmp_path)
326
+ atexit.register(lambda: tmp_path.unlink())
327
+ return tmp_path
328
+
329
+
330
+ def get_python():
331
+ python = Path('python3.9')
332
+ return str(python) if python.exists() else 'python'
333
+
334
+ def get_catboost_config(real_data_path, is_cv=False):
335
+ ds_name = Path(real_data_path).name
336
+ C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
337
+ return C
338
+
339
+ def get_categories(X_train_cat):
340
+ return (
341
+ None
342
+ if X_train_cat is None
343
+ else [
344
+ len(set(X_train_cat[:, i]))
345
+ for i in range(X_train_cat.shape[1])
346
+ ]
347
+ )
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/synthetic/pipeline_c19/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/conftest.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from unittest.mock import MagicMock
6
+
7
+
8
+ # --------------- dimension configs ---------------
9
+
10
+ @pytest.fixture
11
+ def dims():
12
+ """Standard mixed-data dimensions."""
13
+ return {"d_numerical": 4, "categories": np.array([3, 5, 2]), "batch_size": 8, "d_token": 16}
14
+
15
+
16
+ @pytest.fixture
17
+ def dims_numerical_only():
18
+ """Numerical-only scenario (no categorical features)."""
19
+ return {"d_numerical": 5, "categories": None, "batch_size": 8, "d_token": 16}
20
+
21
+
22
+ @pytest.fixture
23
+ def dims_single():
24
+ """Minimal scenario: 1 numerical, 1 categorical with 2 classes."""
25
+ return {"d_numerical": 1, "categories": np.array([2]), "batch_size": 4, "d_token": 8}
26
+
27
+
28
+ # --------------- dummy input factory ---------------
29
+
30
+ @pytest.fixture
31
+ def make_dummy_inputs():
32
+ """Factory: returns (x_num, x_cat_onehot, x_cat_int, timesteps) from any dims."""
33
+ def _make(d_numerical, categories, batch_size):
34
+ torch.manual_seed(42)
35
+ x_num = torch.randn(batch_size, d_numerical)
36
+ if categories is not None and len(categories) > 0:
37
+ cat_parts = []
38
+ for k in categories:
39
+ indices = torch.randint(0, k, (batch_size,))
40
+ cat_parts.append(F.one_hot(indices, k).float())
41
+ x_cat_onehot = torch.cat(cat_parts, dim=1)
42
+ x_cat_int = torch.stack(
43
+ [torch.randint(0, k, (batch_size,)) for k in categories], dim=1
44
+ )
45
+ else:
46
+ x_cat_onehot = None
47
+ x_cat_int = None
48
+ timesteps = torch.rand(batch_size)
49
+ return x_num, x_cat_onehot, x_cat_int, timesteps
50
+ return _make
51
+
52
+
53
+ # --------------- model factories ---------------
54
+
55
+ @pytest.fixture
56
+ def make_tokenizer():
57
+ from ef_vfm.modules.transformer import Tokenizer
58
+ def _make(d_numerical, categories, d_token, bias=True):
59
+ cats = list(categories) if categories is not None else None
60
+ return Tokenizer(d_numerical, cats, d_token, bias)
61
+ return _make
62
+
63
+
64
+ @pytest.fixture
65
+ def make_transformer():
66
+ from ef_vfm.modules.transformer import Transformer
67
+ def _make(d_token, n_layers=2, n_heads=1, d_ffn_factor=4, activation='gelu'):
68
+ return Transformer(n_layers, d_token, n_heads, d_token, d_ffn_factor, activation=activation)
69
+ return _make
70
+
71
+
72
+ @pytest.fixture
73
+ def make_reconstructor():
74
+ from ef_vfm.modules.transformer import Reconstructor
75
+ def _make(d_numerical, categories, d_token):
76
+ cats = list(categories) if categories is not None else []
77
+ return Reconstructor(d_numerical, cats, d_token)
78
+ return _make
79
+
80
+
81
+ @pytest.fixture
82
+ def make_mlp():
83
+ from ef_vfm.modules.main_modules import MLP
84
+ def _make(d_in, dim_t=128, use_mlp=True):
85
+ return MLP(d_in, dim_t=dim_t, use_mlp=use_mlp)
86
+ return _make
87
+
88
+
89
+ @pytest.fixture
90
+ def make_unimodmlp():
91
+ from ef_vfm.modules.main_modules import UniModMLP
92
+ def _make(d_numerical, categories, d_token=16, n_layers=1, n_head=1,
93
+ factor=4, dim_t=64, activation='gelu'):
94
+ cats = list(categories) if categories is not None else []
95
+ return UniModMLP(
96
+ d_numerical, cats, n_layers, d_token,
97
+ n_head=n_head, factor=factor, dim_t=dim_t, activation=activation,
98
+ )
99
+ return _make
100
+
101
+
102
+ @pytest.fixture
103
+ def make_flow_model():
104
+ from ef_vfm.modules.main_modules import UniModMLP
105
+ from ef_vfm.models.flow_model import ExpVFM
106
+ def _make(d_numerical, categories, d_token=16, n_layers=1, dim_t=64):
107
+ cats_list = list(categories) if categories is not None else []
108
+ cats_np = np.array(cats_list)
109
+ model = UniModMLP(
110
+ d_numerical, cats_list, n_layers, d_token,
111
+ n_head=1, factor=4, dim_t=dim_t, activation='gelu',
112
+ )
113
+ flow = ExpVFM(
114
+ num_classes=cats_np,
115
+ num_numerical_features=d_numerical,
116
+ vf_fn=model,
117
+ device=torch.device('cpu'),
118
+ )
119
+ return flow
120
+ return _make
121
+
122
+
123
+ @pytest.fixture
124
+ def make_trainer():
125
+ """Factory: creates a minimal Trainer with mocked external dependencies."""
126
+ from ef_vfm.modules.main_modules import UniModMLP
127
+ from ef_vfm.models.flow_model import ExpVFM
128
+ from ef_vfm.trainer import Trainer
129
+
130
+ def _make(d_numerical=4, categories=np.array([3, 5, 2]),
131
+ lr=0.001, max_grad_norm=1.0, warmup_epochs=0,
132
+ lr_scheduler='reduce_lr_on_plateau', steps=10, tmp_path=None):
133
+
134
+ cats_list = list(categories) if categories is not None else []
135
+ cats_np = np.array(cats_list)
136
+
137
+ model = UniModMLP(
138
+ d_numerical, cats_list, 1, 16,
139
+ n_head=1, factor=4, dim_t=64, activation='gelu',
140
+ )
141
+ flow = ExpVFM(
142
+ num_classes=cats_np,
143
+ num_numerical_features=d_numerical,
144
+ vf_fn=model,
145
+ device=torch.device('cpu'),
146
+ )
147
+
148
+ # Build a small synthetic dataset: [N, d_num + len(cats)] with int cat indices
149
+ n_samples = 32
150
+ x_num = torch.randn(n_samples, d_numerical)
151
+ if len(cats_list) > 0:
152
+ x_cat = torch.stack(
153
+ [torch.randint(0, k, (n_samples,)) for k in cats_list], dim=1
154
+ ).float()
155
+ data = torch.cat([x_num, x_cat], dim=1)
156
+ else:
157
+ data = x_num
158
+
159
+ dataset = torch.utils.data.TensorDataset(data)
160
+ train_iter = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=False)
161
+ # DataLoader wraps in tuples; Trainer expects raw tensors, so use a wrapper
162
+ class _UnwrapLoader:
163
+ def __init__(self, loader):
164
+ self._loader = loader
165
+ def __iter__(self):
166
+ for (batch,) in self._loader:
167
+ yield batch
168
+ def __len__(self):
169
+ return len(self._loader)
170
+
171
+ save_path = str(tmp_path) if tmp_path else "/tmp"
172
+ trainer = Trainer(
173
+ flow=flow,
174
+ train_iter=_UnwrapLoader(train_iter),
175
+ dataset=MagicMock(),
176
+ test_dataset=MagicMock(),
177
+ metrics=MagicMock(),
178
+ logger=MagicMock(),
179
+ lr=lr,
180
+ weight_decay=0,
181
+ steps=steps,
182
+ batch_size=8,
183
+ check_val_every=steps + 1, # never evaluate during test
184
+ sample_batch_size=8,
185
+ model_save_path=save_path,
186
+ result_save_path=save_path,
187
+ lr_scheduler=lr_scheduler,
188
+ max_grad_norm=max_grad_norm,
189
+ warmup_epochs=warmup_epochs,
190
+ device=torch.device('cpu'),
191
+ )
192
+ return trainer
193
+ return _make
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_attention.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ef_vfm.modules.transformer import MultiheadAttention
4
+
5
+
6
+ def test_output_shape_single_head():
7
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
8
+ x = torch.randn(4, 5, 16)
9
+ out = attn(x, x)
10
+ assert out.shape == (4, 5, 16)
11
+
12
+
13
+ def test_output_shape_multi_head():
14
+ attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0)
15
+ x = torch.randn(4, 5, 16)
16
+ out = attn(x, x)
17
+ assert out.shape == (4, 5, 16)
18
+
19
+
20
+ def test_no_W_out_single_head():
21
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
22
+ assert attn.W_out is None
23
+
24
+
25
+ def test_W_out_exists_multi_head():
26
+ attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0)
27
+ assert attn.W_out is not None
28
+
29
+
30
+ def test_cross_attention_diff_seq_len():
31
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
32
+ x_q = torch.randn(4, 3, 16)
33
+ x_kv = torch.randn(4, 7, 16)
34
+ out = attn(x_q, x_kv)
35
+ assert out.shape == (4, 3, 16) # output seq_len matches query
36
+
37
+
38
+ def test_invalid_d_nheads_raises():
39
+ with pytest.raises(AssertionError):
40
+ MultiheadAttention(d=15, n_heads=4, dropout=0.0)
41
+
42
+
43
+ def test_gradient_flows():
44
+ attn = MultiheadAttention(d=16, n_heads=2, dropout=0.0)
45
+ x = torch.randn(4, 5, 16, requires_grad=True)
46
+ out = attn(x, x)
47
+ out.sum().backward()
48
+ assert x.grad is not None and x.grad.abs().sum() > 0
49
+ for name in ['W_q', 'W_k', 'W_v']:
50
+ param = getattr(attn, name)
51
+ assert param.weight.grad is not None and param.weight.grad.abs().sum() > 0
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_config.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from src.util import load_config
5
+ from ef_vfm.modules.main_modules import UniModMLP
6
+
7
+
8
+ CONFIG_PATH = Path(__file__).resolve().parent.parent / "ef_vfm" / "configs" / "ef_vfm_configs.toml"
9
+
10
+
11
+ def test_load_config_returns_dict():
12
+ config = load_config(CONFIG_PATH)
13
+ assert isinstance(config, dict)
14
+
15
+
16
+ def test_config_has_expected_sections():
17
+ config = load_config(CONFIG_PATH)
18
+ for key in ['data', 'unimodmlp_params', 'train', 'sample']:
19
+ assert key in config, f"Missing section '{key}'"
20
+
21
+
22
+ def test_unimodmlp_params_complete():
23
+ config = load_config(CONFIG_PATH)
24
+ params = config['unimodmlp_params']
25
+ required = ['num_layers', 'd_token', 'n_head', 'factor', 'bias', 'dim_t', 'use_mlp', 'activation']
26
+ for key in required:
27
+ assert key in params, f"Missing param '{key}' in unimodmlp_params"
28
+
29
+
30
+ def test_activation_value_is_valid():
31
+ config = load_config(CONFIG_PATH)
32
+ activation = config['unimodmlp_params']['activation']
33
+ assert activation in ('relu', 'gelu', 'silu'), f"Invalid activation '{activation}'"
34
+
35
+
36
+ def test_train_main_has_new_params():
37
+ """Verify the recently added config params are present."""
38
+ config = load_config(CONFIG_PATH)
39
+ train = config['train']['main']
40
+ assert 'max_grad_norm' in train
41
+ assert 'warmup_epochs' in train
42
+ assert isinstance(train['max_grad_norm'], (int, float))
43
+ assert isinstance(train['warmup_epochs'], (int, float))
44
+
45
+
46
+ def test_config_values_create_model():
47
+ config = load_config(CONFIG_PATH)
48
+ params = config['unimodmlp_params']
49
+ # Use dummy dimensions; the point is that config params are valid for the constructor
50
+ model = UniModMLP(
51
+ d_numerical=4,
52
+ categories=[3, 5, 2],
53
+ num_layers=params['num_layers'],
54
+ d_token=params['d_token'],
55
+ n_head=params['n_head'],
56
+ factor=params['factor'],
57
+ bias=params['bias'],
58
+ dim_t=params['dim_t'],
59
+ use_mlp=params['use_mlp'],
60
+ activation=params['activation'],
61
+ )
62
+ assert model is not None
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_flow_model.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from unittest.mock import patch
4
+
5
+ from ef_vfm.models.flow_model import ExpVFM, Velocity
6
+ from ef_vfm.modules.main_modules import UniModMLP
7
+
8
+
9
+ # ---- mixed_loss tests ----
10
+
11
+ def test_mixed_loss_returns_two_scalars(make_flow_model, make_dummy_inputs, dims):
12
+ d = dims
13
+ flow = make_flow_model(d["d_numerical"], d["categories"])
14
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
15
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
16
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
17
+ d_loss, c_loss = flow.mixed_loss(x)
18
+ assert d_loss.dim() == 0 or d_loss.numel() == 1
19
+ assert c_loss.dim() == 0 or c_loss.numel() == 1
20
+
21
+
22
+ def test_mixed_loss_finite(make_flow_model, make_dummy_inputs, dims):
23
+ d = dims
24
+ flow = make_flow_model(d["d_numerical"], d["categories"])
25
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
26
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
27
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
28
+ d_loss, c_loss = flow.mixed_loss(x)
29
+ assert torch.isfinite(d_loss).all()
30
+ assert torch.isfinite(c_loss).all()
31
+
32
+
33
+ def test_mixed_loss_gradients_flow(make_flow_model, make_dummy_inputs, dims):
34
+ d = dims
35
+ flow = make_flow_model(d["d_numerical"], d["categories"])
36
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
37
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
38
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
39
+ d_loss, c_loss = flow.mixed_loss(x)
40
+ total = d_loss + c_loss
41
+ total.backward()
42
+ grads = [p.grad for p in flow.parameters() if p.grad is not None]
43
+ assert len(grads) > 0
44
+
45
+
46
+ def test_mixed_loss_numerical_only(make_flow_model, make_dummy_inputs, dims_numerical_only):
47
+ d = dims_numerical_only
48
+ flow = make_flow_model(d["d_numerical"], d["categories"])
49
+ x = torch.randn(d["batch_size"], d["d_numerical"])
50
+ d_loss, c_loss = flow.mixed_loss(x)
51
+ assert d_loss.item() == 0.0 # no discrete features
52
+ assert c_loss.item() > 0.0
53
+
54
+
55
+ # ---- sample tests (with mocked odeint) ----
56
+
57
+ def _make_flow(d_numerical, categories):
58
+ cats_list = list(categories) if categories is not None else []
59
+ cats_np = np.array(cats_list)
60
+ model = UniModMLP(d_numerical, cats_list, 1, 16, n_head=1, factor=4, dim_t=64, activation='gelu')
61
+ return ExpVFM(cats_np, d_numerical, model, device=torch.device('cpu'))
62
+
63
+
64
+ def test_sample_output_shape(dims):
65
+ d = dims
66
+ flow = _make_flow(d["d_numerical"], d["categories"])
67
+ d_in = d["d_numerical"] + sum(d["categories"])
68
+ n = 5
69
+ fake_trajectory = torch.randn(2, n, d_in)
70
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
71
+ result = flow.sample(n)
72
+ d_out = d["d_numerical"] + len(d["categories"])
73
+ assert result.shape == (n, d_out)
74
+
75
+
76
+ def test_sample_categorical_in_range(dims):
77
+ d = dims
78
+ flow = _make_flow(d["d_numerical"], d["categories"])
79
+ d_in = d["d_numerical"] + sum(d["categories"])
80
+ n = 16
81
+ fake_trajectory = torch.randn(2, n, d_in)
82
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
83
+ result = flow.sample(n)
84
+ for i, k in enumerate(d["categories"]):
85
+ col = d["d_numerical"] + i
86
+ assert (result[:, col] >= 0).all()
87
+ assert (result[:, col] < k).all()
88
+
89
+
90
+ def test_sample_returns_cpu(dims):
91
+ d = dims
92
+ flow = _make_flow(d["d_numerical"], d["categories"])
93
+ d_in = d["d_numerical"] + sum(d["categories"])
94
+ fake_trajectory = torch.randn(2, 4, d_in)
95
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
96
+ result = flow.sample(4)
97
+ assert result.device == torch.device('cpu')
98
+
99
+
100
+ def test_sample_single_sample(dims):
101
+ d = dims
102
+ flow = _make_flow(d["d_numerical"], d["categories"])
103
+ d_in = d["d_numerical"] + sum(d["categories"])
104
+ fake_trajectory = torch.randn(2, 1, d_in)
105
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
106
+ result = flow.sample(1)
107
+ d_out = d["d_numerical"] + len(d["categories"])
108
+ assert result.shape == (1, d_out)
109
+
110
+
111
+ # ---- to_one_hot tests ----
112
+
113
+ def test_to_one_hot_shape(dims):
114
+ d = dims
115
+ flow = _make_flow(d["d_numerical"], d["categories"])
116
+ cats = d["categories"]
117
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
118
+ oh = flow.to_one_hot(x_cat)
119
+ assert oh.shape == (8, sum(cats))
120
+
121
+
122
+ def test_to_one_hot_roundtrip(dims):
123
+ d = dims
124
+ flow = _make_flow(d["d_numerical"], d["categories"])
125
+ cats = d["categories"]
126
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
127
+ oh = flow.to_one_hot(x_cat)
128
+ # Recover indices via argmax per category slice
129
+ idx = 0
130
+ for i, k in enumerate(cats):
131
+ recovered = oh[:, idx:idx + k].argmax(dim=1)
132
+ assert torch.equal(recovered, x_cat[:, i])
133
+ idx += k
134
+
135
+
136
+ def test_to_one_hot_binary_values(dims):
137
+ d = dims
138
+ flow = _make_flow(d["d_numerical"], d["categories"])
139
+ cats = d["categories"]
140
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
141
+ oh = flow.to_one_hot(x_cat)
142
+ assert set(oh.unique().tolist()).issubset({0, 1})
143
+
144
+
145
+ # ---- Regression tests ----
146
+
147
+ def test_regression_d_in_no_extra_len():
148
+ """d_in must be num_numerical + sum(num_classes), NOT + len(num_classes)."""
149
+ d_numerical = 4
150
+ categories = np.array([3, 5, 2])
151
+ flow = _make_flow(d_numerical, categories)
152
+ expected_d_in = d_numerical + sum(categories) # 14, not 17
153
+ assert flow.num_numerical_features + sum(flow.num_classes) == expected_d_in
154
+
155
+
156
+ def test_regression_sampling_indices_correct():
157
+ """Categorical argmax must go to columns [d_num, d_num+1, ...], not [0, 1, ...]."""
158
+ d_numerical = 4
159
+ categories = np.array([3, 5, 2])
160
+ n = 10
161
+ d_in = d_numerical + sum(categories)
162
+ d_out = d_numerical + len(categories)
163
+
164
+ # Simulate the post-processing from sample()
165
+ out = torch.randn(n, d_in)
166
+ sample = torch.zeros(n, d_out)
167
+ sample[:, :d_numerical] = out[:, :d_numerical]
168
+
169
+ idx = d_numerical # correct starting index
170
+ for i, val in enumerate(categories):
171
+ col = d_numerical + i # correct column
172
+ sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1)
173
+ idx += val
174
+
175
+ # Numerical columns must be untouched
176
+ assert torch.allclose(sample[:, :d_numerical], out[:, :d_numerical])
177
+ # Categorical columns at correct positions
178
+ for i, val in enumerate(categories):
179
+ col = d_numerical + i
180
+ assert (sample[:, col] >= 0).all()
181
+ assert (sample[:, col] < val).all()
182
+
183
+
184
+ def test_regression_d_out_correct():
185
+ """d_out must be d_num + len(categories)."""
186
+ d_numerical = 4
187
+ categories = np.array([3, 5, 2])
188
+ flow = _make_flow(d_numerical, categories)
189
+ expected_d_out = d_numerical + len(categories) # 7
190
+ assert expected_d_out == 7
191
+
192
+
193
+ # ---- Velocity tests ----
194
+
195
+ def test_velocity_output_shape(dims):
196
+ d = dims
197
+ cats_list = list(d["categories"])
198
+ model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"],
199
+ n_head=1, factor=4, dim_t=64, activation='gelu')
200
+ vel = Velocity(model)
201
+ d_in = d["d_numerical"] + sum(d["categories"])
202
+ x = torch.randn(d["batch_size"], d_in)
203
+ t = torch.tensor(0.5)
204
+ out = vel(t, x)
205
+ assert out.shape == (d["batch_size"], d_in)
206
+
207
+
208
+ def test_velocity_scalar_t_broadcast(dims):
209
+ d = dims
210
+ cats_list = list(d["categories"])
211
+ model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"],
212
+ n_head=1, factor=4, dim_t=64, activation='gelu')
213
+ vel = Velocity(model)
214
+ d_in = d["d_numerical"] + sum(d["categories"])
215
+ x = torch.randn(d["batch_size"], d_in)
216
+ # Scalar t should work (gets broadcast internally)
217
+ t = torch.tensor(0.3)
218
+ out = vel(t, x)
219
+ assert out.shape == x.shape
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_mlp.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from ef_vfm.modules.main_modules import MLP, PositionalEmbedding
4
+
5
+
6
+ # ---- PositionalEmbedding tests ----
7
+
8
+ def test_positional_embedding_shape():
9
+ pe = PositionalEmbedding(num_channels=64)
10
+ x = torch.rand(8)
11
+ out = pe(x)
12
+ assert out.shape == (8, 64)
13
+
14
+
15
+ def test_positional_embedding_bounded():
16
+ pe = PositionalEmbedding(num_channels=64)
17
+ x = torch.rand(8)
18
+ out = pe(x)
19
+ assert out.min() >= -1.0
20
+ assert out.max() <= 1.0
21
+
22
+
23
+ def test_positional_embedding_deterministic():
24
+ pe = PositionalEmbedding(num_channels=64)
25
+ x = torch.tensor([0.1, 0.5, 0.9])
26
+ out1 = pe(x)
27
+ out2 = pe(x)
28
+ assert torch.equal(out1, out2)
29
+
30
+
31
+ def test_positional_embedding_different_timesteps():
32
+ pe = PositionalEmbedding(num_channels=64)
33
+ t1 = torch.tensor([0.1])
34
+ t2 = torch.tensor([0.9])
35
+ assert not torch.allclose(pe(t1), pe(t2))
36
+
37
+
38
+ # ---- MLP tests ----
39
+
40
+ def test_mlp_output_shape(make_mlp):
41
+ mlp = make_mlp(d_in=32, dim_t=64)
42
+ x = torch.randn(8, 32)
43
+ t = torch.rand(8)
44
+ out = mlp(x, t)
45
+ assert out.shape == (8, 32)
46
+
47
+
48
+ def test_mlp_use_mlp_true(make_mlp):
49
+ mlp = make_mlp(d_in=32, dim_t=64, use_mlp=True)
50
+ assert isinstance(mlp.mlp, nn.Sequential)
51
+
52
+
53
+ def test_mlp_use_mlp_false(make_mlp):
54
+ mlp = make_mlp(d_in=32, dim_t=64, use_mlp=False)
55
+ assert isinstance(mlp.mlp, nn.Linear)
56
+
57
+
58
+ def test_mlp_time_conditioning(make_mlp):
59
+ mlp = make_mlp(d_in=32, dim_t=64)
60
+ mlp.eval()
61
+ x = torch.randn(4, 32)
62
+ t1 = torch.zeros(4)
63
+ t2 = torch.ones(4)
64
+ out1 = mlp(x, t1)
65
+ out2 = mlp(x, t2)
66
+ assert not torch.allclose(out1, out2)
67
+
68
+
69
+ def test_mlp_gradient_flows(make_mlp):
70
+ mlp = make_mlp(d_in=32, dim_t=64)
71
+ x = torch.randn(4, 32)
72
+ t = torch.rand(4)
73
+ out = mlp(x, t)
74
+ out.sum().backward()
75
+ assert mlp.proj.weight.grad is not None and mlp.proj.weight.grad.abs().sum() > 0
76
+ assert mlp.map_noise.num_channels == 64 # sanity check on PE config
77
+
78
+
79
+ def test_mlp_different_dim_t(make_mlp):
80
+ for dim_t in [32, 128, 256]:
81
+ mlp = make_mlp(d_in=16, dim_t=dim_t)
82
+ x = torch.randn(4, 16)
83
+ t = torch.rand(4)
84
+ out = mlp(x, t)
85
+ assert out.shape == (4, 16)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_reconstructor.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from ef_vfm.modules.transformer import Reconstructor
4
+
5
+
6
+ def test_output_shapes_mixed(make_reconstructor, dims):
7
+ d = dims
8
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
9
+ seq_len = d["d_numerical"] + len(d["categories"])
10
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
11
+ x_num, x_cat = r(h)
12
+ assert x_num.shape == (d["batch_size"], d["d_numerical"])
13
+ assert len(x_cat) == len(d["categories"])
14
+ for i, k in enumerate(d["categories"]):
15
+ assert x_cat[i].shape == (d["batch_size"], k)
16
+
17
+
18
+ def test_categorical_count(make_reconstructor, dims):
19
+ d = dims
20
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
21
+ seq_len = d["d_numerical"] + len(d["categories"])
22
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
23
+ _, x_cat = r(h)
24
+ assert len(x_cat) == len(d["categories"])
25
+
26
+
27
+ def test_empty_categories(make_reconstructor):
28
+ r = make_reconstructor(4, np.array([]), 16)
29
+ h = torch.randn(8, 4, 16)
30
+ x_num, x_cat = r(h)
31
+ assert x_num.shape == (8, 4)
32
+ assert len(x_cat) == 0
33
+
34
+
35
+ def test_weight_shape(make_reconstructor, dims):
36
+ d = dims
37
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
38
+ assert r.weight.shape == (d["d_numerical"], d["d_token"])
39
+
40
+
41
+ def test_gradient_flows(make_reconstructor, dims):
42
+ d = dims
43
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
44
+ seq_len = d["d_numerical"] + len(d["categories"])
45
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
46
+ x_num, x_cat = r(h)
47
+ loss = x_num.sum() + sum(c.sum() for c in x_cat)
48
+ loss.backward()
49
+ assert r.weight.grad is not None and r.weight.grad.abs().sum() > 0
50
+ for recon in r.cat_recons:
51
+ assert recon.weight.grad is not None
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_tokenizer.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ def test_forward_shape_mixed(make_tokenizer, make_dummy_inputs, dims):
6
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
7
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
8
+ out = tok(x_num, x_cat_oh)
9
+ expected_seq = 1 + dims["d_numerical"] + len(dims["categories"])
10
+ assert out.shape == (dims["batch_size"], expected_seq, dims["d_token"])
11
+
12
+
13
+ def test_forward_shape_numerical_only(make_tokenizer, make_dummy_inputs, dims_numerical_only):
14
+ d = dims_numerical_only
15
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
16
+ x_num, _, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
17
+ out = tok(x_num, None)
18
+ expected_seq = 1 + d["d_numerical"]
19
+ assert out.shape == (d["batch_size"], expected_seq, d["d_token"])
20
+
21
+
22
+ def test_forward_shape_single_feature(make_tokenizer, make_dummy_inputs, dims_single):
23
+ d = dims_single
24
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
25
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
26
+ out = tok(x_num, x_cat_oh)
27
+ expected_seq = 1 + d["d_numerical"] + len(d["categories"])
28
+ assert out.shape == (d["batch_size"], expected_seq, d["d_token"])
29
+
30
+
31
+ def test_n_tokens_property(make_tokenizer, dims):
32
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
33
+ expected = dims["d_numerical"] + 1 + len(dims["categories"])
34
+ assert tok.n_tokens == expected
35
+
36
+
37
+ def test_n_tokens_numerical_only(make_tokenizer, dims_numerical_only):
38
+ d = dims_numerical_only
39
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
40
+ assert tok.n_tokens == d["d_numerical"] + 1
41
+
42
+
43
+ def test_cls_token_position(make_tokenizer, make_dummy_inputs, dims):
44
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"], bias=False)
45
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
46
+ out = tok(x_num, x_cat_oh)
47
+ # CLS token: ones * weight[0], so all batch rows should have the same CLS token
48
+ cls_tokens = out[:, 0, :]
49
+ assert torch.allclose(cls_tokens[0], cls_tokens[1])
50
+ assert torch.allclose(cls_tokens[0], tok.weight[0])
51
+
52
+
53
+ def test_bias_vs_no_bias(make_tokenizer, make_dummy_inputs, dims):
54
+ d = dims
55
+ tok_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=True)
56
+ tok_no_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=False)
57
+ assert tok_bias.bias is not None
58
+ assert tok_no_bias.bias is None
59
+
60
+
61
+ def test_category_offsets_values(make_tokenizer):
62
+ cats = np.array([3, 5, 2])
63
+ tok = make_tokenizer(4, cats, 16)
64
+ assert torch.equal(tok.category_offsets, torch.tensor([0, 3, 8]))
65
+ assert torch.equal(tok.category_ends, torch.tensor([3, 8, 10]))
66
+
67
+
68
+ def test_cat_weight_shape(make_tokenizer, dims):
69
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
70
+ assert tok.cat_weight.shape == (sum(dims["categories"]), dims["d_token"])
71
+
72
+
73
+ def test_weight_shape(make_tokenizer, dims):
74
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
75
+ assert tok.weight.shape == (dims["d_numerical"] + 1, dims["d_token"])
76
+
77
+
78
+ def test_gradient_flows(make_tokenizer, make_dummy_inputs, dims):
79
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
80
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
81
+ out = tok(x_num, x_cat_oh)
82
+ out.sum().backward()
83
+ assert tok.weight.grad is not None and tok.weight.grad.abs().sum() > 0
84
+ assert tok.cat_weight.grad is not None and tok.cat_weight.grad.abs().sum() > 0
85
+ assert tok.bias.grad is not None and tok.bias.grad.abs().sum() > 0
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_trainer.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ # ---- Gradient clipping tests ----
6
+
7
+ def test_grad_clipping_applied(make_trainer, tmp_path):
8
+ trainer = make_trainer(max_grad_norm=0.5, tmp_path=tmp_path)
9
+ batch = next(iter(trainer.train_iter))
10
+ trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0)
11
+ # After clipping, total gradient norm should be <= max_grad_norm (with tolerance)
12
+ total_norm = torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), float('inf'))
13
+ # Gradients were already clipped in _run_step, then optimizer.step() zeroed them.
14
+ # So we re-run to check: do a fresh forward-backward without step
15
+ trainer.optimizer.zero_grad()
16
+ dloss, closs = trainer.flow.mixed_loss(batch.to(trainer.device))
17
+ (dloss + closs).backward()
18
+ torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), 0.5)
19
+ total_norm = 0.0
20
+ for p in trainer.flow.parameters():
21
+ if p.grad is not None:
22
+ total_norm += p.grad.data.norm(2).item() ** 2
23
+ total_norm = total_norm ** 0.5
24
+ assert total_norm <= 0.5 + 1e-6
25
+
26
+
27
+ def test_grad_clipping_disabled(make_trainer, tmp_path):
28
+ trainer = make_trainer(max_grad_norm=0, tmp_path=tmp_path)
29
+ assert trainer.max_grad_norm == 0
30
+
31
+
32
+ def test_run_step_returns_losses(make_trainer, tmp_path):
33
+ trainer = make_trainer(tmp_path=tmp_path)
34
+ batch = next(iter(trainer.train_iter))
35
+ dloss, closs = trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0)
36
+ assert isinstance(dloss, torch.Tensor)
37
+ assert isinstance(closs, torch.Tensor)
38
+ assert torch.isfinite(dloss)
39
+ assert torch.isfinite(closs)
40
+
41
+
42
+ # ---- LR warmup tests ----
43
+
44
+ def test_warmup_lr_linear_ramp(make_trainer, tmp_path):
45
+ init_lr = 0.01
46
+ warmup = 5
47
+ trainer = make_trainer(lr=init_lr, warmup_epochs=warmup, tmp_path=tmp_path)
48
+ # Simulate warmup epochs
49
+ for epoch in range(warmup):
50
+ expected_lr = init_lr * (epoch + 1) / warmup
51
+ if trainer.warmup_epochs > 0 and (epoch + 1) <= trainer.warmup_epochs:
52
+ warmup_lr = trainer.init_lr * (epoch + 1) / trainer.warmup_epochs
53
+ for pg in trainer.optimizer.param_groups:
54
+ pg["lr"] = warmup_lr
55
+ actual_lr = trainer.optimizer.param_groups[0]["lr"]
56
+ assert abs(actual_lr - expected_lr) < 1e-8, f"Epoch {epoch}: expected {expected_lr}, got {actual_lr}"
57
+
58
+
59
+ def test_warmup_overrides_scheduler(make_trainer, tmp_path):
60
+ trainer = make_trainer(warmup_epochs=10, lr_scheduler='reduce_lr_on_plateau', tmp_path=tmp_path)
61
+ initial_lr = trainer.optimizer.param_groups[0]["lr"]
62
+ # During warmup, scheduler.step should NOT be called (we just set LR directly)
63
+ # Simulate epoch 1 warmup
64
+ warmup_lr = trainer.init_lr * 1 / trainer.warmup_epochs
65
+ for pg in trainer.optimizer.param_groups:
66
+ pg["lr"] = warmup_lr
67
+ assert trainer.optimizer.param_groups[0]["lr"] == warmup_lr
68
+ assert warmup_lr < initial_lr # warmup starts lower
69
+
70
+
71
+ def test_no_warmup_when_zero(make_trainer, tmp_path):
72
+ trainer = make_trainer(warmup_epochs=0, tmp_path=tmp_path)
73
+ assert trainer.warmup_epochs == 0
74
+ # LR should be the init_lr from the start
75
+ assert trainer.optimizer.param_groups[0]["lr"] == trainer.init_lr
76
+
77
+
78
+ # ---- LR scheduler tests ----
79
+
80
+ def test_anneal_lr(make_trainer, tmp_path):
81
+ trainer = make_trainer(lr=0.01, steps=100, lr_scheduler='anneal', tmp_path=tmp_path)
82
+ trainer._anneal_lr(50)
83
+ expected = 0.01 * (1 - 50 / 100)
84
+ assert abs(trainer.optimizer.param_groups[0]["lr"] - expected) < 1e-8
85
+
86
+
87
+ # ---- EMA tests ----
88
+
89
+ def test_ema_model_created(make_trainer, tmp_path):
90
+ trainer = make_trainer(tmp_path=tmp_path)
91
+ # EMA model should exist and have same structure as flow._vf_fn
92
+ assert trainer.ema_model is not None
93
+ ema_params = list(trainer.ema_model.parameters())
94
+ model_params = list(trainer.flow._vf_fn.parameters())
95
+ assert len(ema_params) == len(model_params)
96
+ # EMA params should be detached (requires_grad=False)
97
+ for p in ema_params:
98
+ assert not p.requires_grad
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_transformer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ef_vfm.modules.transformer import Transformer
4
+
5
+
6
+ def test_output_shape_preserved(make_transformer):
7
+ t = make_transformer(d_token=16, n_layers=2)
8
+ x = torch.randn(4, 5, 16)
9
+ out = t(x)
10
+ assert out.shape == x.shape
11
+
12
+
13
+ def test_activation_gelu(make_transformer):
14
+ t = make_transformer(d_token=16, activation='gelu')
15
+ x = torch.randn(4, 5, 16)
16
+ out = t(x)
17
+ assert out.shape == x.shape
18
+
19
+
20
+ def test_activation_silu(make_transformer):
21
+ t = make_transformer(d_token=16, activation='silu')
22
+ x = torch.randn(4, 5, 16)
23
+ out = t(x)
24
+ assert out.shape == x.shape
25
+
26
+
27
+ def test_activation_relu(make_transformer):
28
+ t = make_transformer(d_token=16, activation='relu')
29
+ x = torch.randn(4, 5, 16)
30
+ out = t(x)
31
+ assert out.shape == x.shape
32
+
33
+
34
+ def test_invalid_activation_raises():
35
+ with pytest.raises(ValueError, match="Unknown activation"):
36
+ Transformer(2, 16, 1, 16, 4, activation='bad')
37
+
38
+
39
+ def test_prenorm_first_layer_no_norm0():
40
+ t = Transformer(2, 16, 1, 16, 4, prenormalization=True)
41
+ assert 'norm0' not in t.layers[0]
42
+ # Second layer should have norm0
43
+ assert 'norm0' in t.layers[1]
44
+
45
+
46
+ def test_no_prenorm_all_layers_have_norm0():
47
+ t = Transformer(2, 16, 1, 16, 4, prenormalization=False)
48
+ for layer in t.layers:
49
+ assert 'norm0' in layer
50
+
51
+
52
+ def test_single_layer():
53
+ t = Transformer(1, 16, 1, 16, 4)
54
+ x = torch.randn(4, 5, 16)
55
+ out = t(x)
56
+ assert out.shape == x.shape
57
+
58
+
59
+ def test_multi_layer():
60
+ t = Transformer(4, 16, 1, 16, 4)
61
+ x = torch.randn(4, 5, 16)
62
+ out = t(x)
63
+ assert out.shape == x.shape
64
+
65
+
66
+ def test_gradient_flows(make_transformer):
67
+ t = make_transformer(d_token=16, n_layers=2)
68
+ x = torch.randn(4, 5, 16, requires_grad=True)
69
+ out = t(x)
70
+ out.sum().backward()
71
+ assert x.grad is not None and x.grad.abs().sum() > 0
72
+ # Check gradients through at least the first layer's linear0
73
+ assert t.layers[0]['linear0'].weight.grad is not None
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_unimodmlp.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ def test_forward_shapes_mixed(make_unimodmlp, make_dummy_inputs, dims):
6
+ d = dims
7
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
8
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
9
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
10
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
11
+ assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"]))
12
+
13
+
14
+ def test_forward_shapes_numerical_only(make_unimodmlp, make_dummy_inputs, dims_numerical_only):
15
+ d = dims_numerical_only
16
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
17
+ x_num, _, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
18
+ x_cat = torch.zeros(d["batch_size"], 0)
19
+ x_num_pred, x_cat_pred = model(x_num, x_cat, t)
20
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
21
+ # When no categories, cat_pred should be zeros with shape matching x_cat
22
+ assert x_cat_pred.shape[0] == d["batch_size"]
23
+ assert torch.all(x_cat_pred == 0)
24
+
25
+
26
+ def test_forward_shapes_single_feature(make_unimodmlp, make_dummy_inputs, dims_single):
27
+ d = dims_single
28
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
29
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
30
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
31
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
32
+ assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"]))
33
+
34
+
35
+ def test_d_in_computation(make_unimodmlp, dims):
36
+ d = dims
37
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
38
+ expected = d["d_token"] * (d["d_numerical"] + len(d["categories"]))
39
+ assert model.mlp.proj.in_features == expected
40
+
41
+
42
+ def test_output_dtypes(make_unimodmlp, make_dummy_inputs, dims):
43
+ d = dims
44
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
45
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
46
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
47
+ assert x_num_pred.dtype == torch.float32
48
+ assert x_cat_pred.dtype == torch.float32
49
+
50
+
51
+ def test_gradient_flows_end_to_end(make_unimodmlp, make_dummy_inputs, dims):
52
+ d = dims
53
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
54
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
55
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
56
+ loss = x_num_pred.sum() + x_cat_pred.sum()
57
+ loss.backward()
58
+ params_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0)
59
+ total_params = sum(1 for _ in model.parameters())
60
+ # Transformer.head is defined but unused in forward(), so not all params get gradients
61
+ assert params_with_grad > total_params * 0.8, f"Only {params_with_grad}/{total_params} params got gradients"
62
+
63
+
64
+ def test_different_activations(make_unimodmlp, make_dummy_inputs, dims):
65
+ d = dims
66
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
67
+ for act in ['relu', 'gelu', 'silu']:
68
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"], activation=act)
69
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
70
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
71
+ assert torch.isfinite(x_num_pred).all()
72
+ assert torch.isfinite(x_cat_pred).all()
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/tests/test_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ from utils_train import update_ema, concat_y_to_X
5
+
6
+
7
+ # ---- update_ema tests ----
8
+
9
+ def test_update_ema_basic():
10
+ target = [torch.tensor([1.0, 2.0])]
11
+ source = [torch.tensor([3.0, 4.0])]
12
+ target[0].requires_grad_(False)
13
+ rate = 0.9
14
+ update_ema(target, source, rate=rate)
15
+ expected = 0.9 * torch.tensor([1.0, 2.0]) + 0.1 * torch.tensor([3.0, 4.0])
16
+ assert torch.allclose(target[0], expected)
17
+
18
+
19
+ def test_update_ema_rate_zero():
20
+ target = [torch.tensor([1.0, 2.0])]
21
+ source = [torch.tensor([3.0, 4.0])]
22
+ target[0].requires_grad_(False)
23
+ update_ema(target, source, rate=0.0)
24
+ assert torch.allclose(target[0], torch.tensor([3.0, 4.0]))
25
+
26
+
27
+ def test_update_ema_rate_one():
28
+ target = [torch.tensor([1.0, 2.0])]
29
+ source = [torch.tensor([3.0, 4.0])]
30
+ target[0].requires_grad_(False)
31
+ update_ema(target, source, rate=1.0)
32
+ assert torch.allclose(target[0], torch.tensor([1.0, 2.0]))
33
+
34
+
35
+ # ---- concat_y_to_X tests ----
36
+
37
+ def test_concat_y_to_X_with_X():
38
+ X = np.array([[1, 2], [3, 4]])
39
+ y = np.array([10, 20])
40
+ result = concat_y_to_X(X, y)
41
+ expected = np.array([[10, 1, 2], [20, 3, 4]])
42
+ np.testing.assert_array_equal(result, expected)
43
+
44
+
45
+ def test_concat_y_to_X_without_X():
46
+ y = np.array([10, 20, 30])
47
+ result = concat_y_to_X(None, y)
48
+ expected = np.array([[10], [20], [30]])
49
+ np.testing.assert_array_equal(result, expected)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/utils_train.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+
4
+ import src
5
+ from torch.utils.data import Dataset
6
+
7
+ import torch
8
+
9
+
10
+ class TabularDataset(Dataset):
11
+ def __init__(self, X_num, X_cat):
12
+ self.X_num = X_num
13
+ self.X_cat = X_cat
14
+
15
+ def __getitem__(self, index):
16
+ this_num = self.X_num[index]
17
+ this_cat = self.X_cat[index]
18
+
19
+ sample = (this_num, this_cat)
20
+
21
+ return sample
22
+
23
+ def __len__(self):
24
+ return self.X_num.shape[0]
25
+
26
+ class EFVFMDataset(Dataset):
27
+ def __init__(self, dataname, data_dir, info, isTrain=True, dequant_dist='none', int_dequant_factor=0.0):
28
+ self.dataname = dataname
29
+ self.data_dir = data_dir
30
+ self.info = info
31
+ self.isTrain = isTrain
32
+
33
+ X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse = preprocess(data_dir, dequant_dist, int_dequant_factor, task_type = info['task_type'], inverse=True)
34
+ categories = np.array(categories)
35
+
36
+ X_train_num, _ = X_num
37
+ X_train_cat, _ = X_cat
38
+
39
+ X_train_num, X_test_num = X_num
40
+ X_train_cat, X_test_cat = X_cat
41
+
42
+ X_train_num, X_test_num = torch.tensor(X_train_num).float(), torch.tensor(X_test_num).float()
43
+ X_train_cat, X_test_cat = torch.tensor(X_train_cat), torch.tensor(X_test_cat)
44
+
45
+ self.X = torch.cat((X_train_num, X_train_cat), dim=1) if isTrain else torch.cat((X_test_num, X_test_cat), dim=1)
46
+ self.num_inverse = num_inverse
47
+ self.int_inverse = int_inverse
48
+ self.cat_inverse = cat_inverse
49
+ self.d_numerical = d_numerical
50
+ self.categories = categories
51
+
52
+ def __getitem__(self, index):
53
+ return self.X[index]
54
+
55
+ def __len__(self):
56
+ return self.X.shape[0]
57
+
58
+ def preprocess(dataset_path, dequant_dist='none', int_dequant_factor=0.0, task_type = 'binclass', inverse = False, cat_encoding = None, concat = True):
59
+
60
+ T_dict = {}
61
+
62
+ T_dict['normalization'] = "quantile"
63
+ T_dict['num_nan_policy'] = 'mean'
64
+ T_dict['cat_nan_policy'] = None
65
+ T_dict['cat_min_frequency'] = None
66
+ T_dict['cat_encoding'] = cat_encoding
67
+ T_dict['y_policy'] = "default"
68
+ T_dict['dequant_dist'] = dequant_dist
69
+ T_dict['int_dequant_factor'] = int_dequant_factor
70
+
71
+ T = src.Transformations(**T_dict)
72
+
73
+ dataset = make_dataset(
74
+ data_path = dataset_path,
75
+ T = T,
76
+ task_type = task_type,
77
+ change_val = False,
78
+ concat = concat,
79
+ )
80
+
81
+ if cat_encoding is None:
82
+ X_num = dataset.X_num
83
+ X_cat = dataset.X_cat
84
+
85
+ X_train_num, X_test_num = X_num['train'], X_num['test']
86
+ X_train_cat, X_test_cat = X_cat['train'], X_cat['test']
87
+
88
+ categories = src.get_categories(X_train_cat)
89
+ d_numerical = X_train_num.shape[1]
90
+
91
+ X_num = (X_train_num, X_test_num)
92
+ X_cat = (X_train_cat, X_test_cat)
93
+
94
+
95
+ if inverse:
96
+ num_inverse = dataset.num_transform.inverse_transform if dataset.num_transform is not None else lambda x: x
97
+ int_inverse = dataset.int_transform.inverse_transform if dataset.int_transform is not None else lambda x: x
98
+ cat_inverse = dataset.cat_transform.inverse_transform if dataset.cat_transform is not None else lambda x: x
99
+
100
+ return X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse
101
+ else:
102
+ return X_num, X_cat, categories, d_numerical
103
+ else:
104
+ return dataset
105
+
106
+
107
+ def update_ema(target_params, source_params, rate=0.999):
108
+ """
109
+ Update target parameters to be closer to those of source parameters using
110
+ an exponential moving average.
111
+ :param target_params: the target parameter sequence.
112
+ :param source_params: the source parameter sequence.
113
+ :param rate: the EMA rate (closer to 1 means slower).
114
+ """
115
+ for target, source in zip(target_params, source_params):
116
+ target.detach().mul_(rate).add_(source.detach(), alpha=1 - rate)
117
+
118
+
119
+
120
+ def concat_y_to_X(X, y):
121
+ if X is None:
122
+ return y.reshape(-1, 1)
123
+ return np.concatenate([y.reshape(-1, 1), X], axis=1)
124
+
125
+
126
+ def make_dataset(
127
+ data_path: str,
128
+ T: src.Transformations,
129
+ task_type,
130
+ change_val: bool,
131
+ concat = True,
132
+ ):
133
+
134
+ # classification
135
+ if task_type == 'binclass' or task_type == 'multiclass':
136
+ X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None
137
+ X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None
138
+ y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None
139
+
140
+ for split in ['train', 'test']:
141
+ X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split)
142
+ if X_num is not None:
143
+ X_num[split] = X_num_t
144
+ if X_cat is not None:
145
+ if concat:
146
+ X_cat_t = concat_y_to_X(X_cat_t, y_t)
147
+ X_cat[split] = X_cat_t
148
+ if y is not None:
149
+ y[split] = y_t
150
+ else:
151
+ # regression
152
+ X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None
153
+ X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None
154
+ y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None
155
+
156
+ for split in ['train', 'test']:
157
+ X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split)
158
+ if X_num is not None:
159
+ if concat:
160
+ X_num_t = concat_y_to_X(X_num_t, y_t)
161
+ X_num[split] = X_num_t
162
+ if X_cat is not None:
163
+ X_cat[split] = X_cat_t
164
+ if y is not None:
165
+ y[split] = y_t
166
+
167
+ info = src.load_json(os.path.join(data_path, 'info.json'))
168
+ int_col_idx_wrt_num = info['int_col_idx_wrt_num']
169
+
170
+ D = src.Dataset(
171
+ X_num,
172
+ X_cat,
173
+ y,
174
+ int_col_idx_wrt_num,
175
+ y_info={},
176
+ task_type=src.TaskType(info['task_type']),
177
+ n_classes=info.get('n_classes')
178
+ )
179
+
180
+ if change_val:
181
+ D = src.change_val(D)
182
+
183
+ return src.transform_dataset(D, T, None)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_tabbyflow_gen.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ root = r"/workspace/ef-vfm"
4
+ rt = r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime"
5
+ name = r"pipeline_c19"
6
+ src = r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19"
7
+
8
+ if not os.path.exists(rt):
9
+ def _ignore(_, names):
10
+ skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
11
+ return [n for n in names if n in skip or n.endswith(".pyc")]
12
+ shutil.copytree(root, rt, ignore=_ignore)
13
+
14
+ dst_data = os.path.join(rt, "data", name)
15
+ shutil.rmtree(dst_data, ignore_errors=True)
16
+ os.makedirs(os.path.dirname(dst_data), exist_ok=True)
17
+ shutil.copytree(src, dst_data)
18
+ dst_syn = os.path.join(rt, "synthetic", name)
19
+ os.makedirs(dst_syn, exist_ok=True)
20
+ for fn in ("real.csv", "test.csv", "val.csv"):
21
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
22
+ os.chdir(rt)
23
+ os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "")
24
+ os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "128")
25
+ subprocess.check_call([
26
+ sys.executable, os.path.join(rt, "main.py"),
27
+ "--dataname", name, "--mode", "test", "--gpu", "0",
28
+ "--no_wandb", "--exp_name", r"adapter_efvfm",
29
+ "--ckpt_path", r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/model_100.pt",
30
+ "--num_samples_to_generate", str(int(32759)),
31
+ ])
32
+ base = os.path.join(rt, "ef_vfm", "result", name, r"adapter_efvfm")
33
+ best = None
34
+ best_t = -1.0
35
+ for r, _, files in os.walk(base):
36
+ if "samples.csv" in files:
37
+ p = os.path.join(r, "samples.csv")
38
+ t = os.path.getmtime(p)
39
+ if t > best_t:
40
+ best_t, best = t, p
41
+ if not best:
42
+ raise SystemExit("tabbyflow: no samples.csv in " + base)
43
+ shutil.copy(best, r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow-c19-32759-20260510_210653.csv")
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_tabbyflow_train.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ root = r"/workspace/ef-vfm"
4
+ rt = r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime"
5
+ name = r"pipeline_c19"
6
+ src = r"/work/output-Benchmark-trainonly-v1/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19"
7
+
8
+ shutil.rmtree(rt, ignore_errors=True)
9
+
10
+ def _ignore(_, names):
11
+ skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
12
+ return [n for n in names if n in skip or n.endswith(".pyc")]
13
+
14
+ shutil.copytree(root, rt, ignore=_ignore)
15
+ dst_data = os.path.join(rt, "data", name)
16
+ dst_syn = os.path.join(rt, "synthetic", name)
17
+ shutil.rmtree(dst_data, ignore_errors=True)
18
+ os.makedirs(os.path.dirname(dst_data), exist_ok=True)
19
+ shutil.copytree(src, dst_data)
20
+ os.makedirs(dst_syn, exist_ok=True)
21
+ for fn in ("real.csv", "test.csv", "val.csv"):
22
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
23
+ os.chdir(rt)
24
+ os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "")
25
+ os.environ["EFVFM_SMOKE_STEPS"] = "100"
26
+ os.environ["EFVFM_ADAPTER_TRAIN"] = "1"
27
+ os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "128")
28
+ os.environ.setdefault("EFVFM_EVAL_NUM_SAMPLES", "512")
29
+ subprocess.check_call([
30
+ sys.executable, os.path.join(rt, "main.py"),
31
+ "--dataname", name, "--mode", "train", "--gpu", "0",
32
+ "--no_wandb", "--exp_name", r"adapter_efvfm",
33
+ ])
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/gen_20260510_210653.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31d33869b2d66e790b37e1e95568a8c2fd723b7778f77cadcb9c0d8f01f97a6c
3
+ size 11605
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/input_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a6ec1d6050eca471b7e315b6e1853a0caf2f267f24a058ba610ed5ed871159c
3
+ size 1367
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/models_tabbyflow/trained.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adb734fec12f2251befd371dca69e481b19464aded2a6823105a01b4be6ddbe5
3
+ size 40
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/normalized_schema_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29277905718aadff6392f1a493cc90a009209da285eb3c9cfaa6ed315532ed07
3
+ size 15890
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/public_gate_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f3b9879993ec6898672e12c529e80204564945d19d90073329035241094707d
3
+ size 925
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/public_gate/staged_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18efa052ebf7acfceb2a946281888d96a451259dae53034620c99652b1b65f31
3
+ size 16726
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/run_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56ca79b893451e730321415e85bdeb6b4f925dffdcbe29e481681fb92fcc7980
3
+ size 2130
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/runtime_result.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:484b401fb61e1d46d8745b4135055567641e30ba89783be7f29926ee16f3e286
3
+ size 933
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948
3
+ size 1564
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/public/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba9507a65d486c834e0e4db94ef9cc0a58be72f5b099138629213c8c93d02fc6
3
+ size 329
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/adapter_transforms_applied.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
3
+ size 2
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/staged/tabbyflow/model_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:999e46e2362092f92781dca68a6bf7e22e7bbc0edad665b7150a83154ef17658
3
+ size 16931
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow-c19-32759-20260510_210653.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0987e8c8e00cc2fe06cdc59415e2bc32fc5509f3f2de9bc33ca93e3dba2c825
3
+ size 3040256
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabbyflow_train_meta.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc462a1d79b96f876d4400ed904699529d43f6df58149443deb01576c2262ddd
3
+ size 421
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e8e273d7cebc9c535de23aac186a248e19f1b9270192e8516df2b3ff4d03b37
3
+ size 360576
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34a72bf9b360ceafc923a841725257c58f68702db5988848164e6a73030811ca
3
+ size 2882920
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_cat_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7520984bdd5518919a6429f53fe78669a4c04ec06e58bb0b5388e56628d3080
3
+ size 360400
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30bb71265025b7923a442d2e4818d163e76ace6a48bd5be6e29de20770bc8e15
3
+ size 65664
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42ba0171576b4338cee3594e553bc298640933ba7a7c8a127ec106b642ee63e6
3
+ size 524272
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adb8a29c75d7bdc3c8f7e797e555998c90f3b3154ccaeee3dc93d8cbe6c3c2d1
3
+ size 65632
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26b65c13dd436fb96a31e3ea486b261897b74f9a192fe79828dc57be59be2f35
3
+ size 2739
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948
3
+ size 1564
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589