{"record":{"id":"43cb2d9ce3fa0bff","repo":"microsoft/qlib","slug":"unsupported-reweighter-type-43cb2d","errorCode":null,"errorMessage":"Unsupported reweighter type.","messagePattern":"Unsupported reweighter type\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_nn.py","lineNumber":216,"sourceCode":"        has_valid = \"valid\" in dataset.segments\n        segments = [\"train\", \"valid\"]\n        vars = [\"x\", \"y\", \"w\"]\n        all_df = defaultdict(dict)  # x_train, x_valid y_train, y_valid w_train, w_valid\n        all_t = defaultdict(dict)  # tensors\n        for seg in segments:\n            if seg in dataset.segments:\n                # df_train df_valid\n                df = dataset.prepare(\n                    seg, col_set=[\"feature\", \"label\"], data_key=self.valid_key if seg == \"valid\" else DataHandlerLP.DK_L\n                )\n                all_df[\"x\"][seg] = df[\"feature\"]\n                all_df[\"y\"][seg] = df[\"label\"].copy()  # We have to use copy to remove the reference to release mem\n                if reweighter is None:\n                    all_df[\"w\"][seg] = pd.DataFrame(np.ones_like(all_df[\"y\"][seg].values), index=df.index)\n                elif isinstance(reweighter, Reweighter):\n                    all_df[\"w\"][seg] = pd.DataFrame(reweighter.reweight(df))\n                else:\n                    raise ValueError(\"Unsupported reweighter type.\")\n\n                # get tensors\n                for v in vars:\n                    all_t[v][seg] = torch.from_numpy(all_df[v][seg].values).float()\n                    # if seg == \"valid\": # accelerate the eval of validation\n                    all_t[v][seg] = all_t[v][seg].to(self.device)  # This will consume a lot of memory !!!!\n\n                evals_result[seg] = []\n                # free memory\n                del df\n                del all_df[\"x\"]\n                gc.collect()\n\n        save_path = get_or_create_path(save_path)\n        stop_steps = 0\n        train_loss = 0\n        best_loss = np.inf\n        # train","sourceCodeStart":198,"sourceCodeEnd":234,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_nn.py#L198-L234","documentation":"DNNModelPytorch.fit() builds sample weights per segment: reweighter=None gives uniform ones; a qlib.dataset.common.Reweighter instance has its reweight(df) called; anything else raises ValueError('Unsupported reweighter type.') while preparing train/valid data, before training starts.","triggerScenarios":"model.fit(dataset, reweighter=X) with X not None and not an instance of qlib.dataset.common.Reweighter — e.g. a weight array, pandas Series, lambda, or duck-typed custom class lacking the subclass relationship.","commonSituations":"Hand-rolling sample weights as arrays/callables; using a reweighter class copied from another project that doesn't subclass qlib's Reweighter; misunderstanding that the API is type-based, not duck-typed.","solutions":["Subclass qlib.data.dataset.Reweighter and implement reweight(self, data_frame) returning per-sample weights; pass that instance.","Pass reweighter=None (or omit) when you don't need weighting.","For builtin weighting schemes, check qlib's existing Reweighter implementations and reuse them."],"exampleFix":"# before\nmodel.fit(dataset, reweighter=lambda df: df[\"label\"] ** 2)  # ValueError: Unsupported reweighter type.\n\n# after\nfrom qlib.data.dataset import Reweighter\n\nclass AbsLabelReweighter(Reweighter):\n    def reweight(self, data_frame):\n        return data_frame[\"label\"].abs().values\n\nmodel.fit(dataset, reweighter=AbsLabelReweighter())","handlingStrategy":"type-guard","validationCode":"from qlib.data.dataset import Reweighter\n\nif reweighter is not None and not isinstance(reweighter, Reweighter):\n    raise TypeError(\"reweighter must be None or a qlib Reweighter instance\")\nmodel.fit(dataset, reweighter=reweighter)","typeGuard":"from qlib.data.dataset import Reweighter\n\ndef is_valid_reweighter(rw) -> bool:\n    return rw is None or isinstance(rw, Reweighter)","tryCatchPattern":"try:\n    model.fit(dataset, reweighter=rw)\nexcept ValueError as e:\n    if \"Unsupported reweighter\" in str(e):\n        raise TypeError(\"Wrap weighting logic in a qlib Reweighter subclass\") from e\n    raise","preventionTips":["Wrap any weighting scheme in a Reweighter subclass with reweight(df) returning per-sample weights.","The check is isinstance-based; duck typing is rejected by design.","Pass None explicitly when uniform weights are intended."],"tags":["pytorch","qlib","reweighter","dnn","type-validation"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}