{"record":{"id":"77a0fcbb0078fa66","repo":"microsoft/qlib","slug":"unsupported-reweighter-type-77a0fc","errorCode":null,"errorMessage":"Unsupported reweighter type.","messagePattern":"Unsupported reweighter type\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_general_nn.py","lineNumber":258,"sourceCode":"        reweighter=None,\n    ):\n        ists = isinstance(dataset, TSDatasetH)  # is this time series dataset\n\n        dl_train = dataset.prepare(\"train\", col_set=[\"feature\", \"label\"], data_key=DataHandlerLP.DK_L)\n        dl_valid = dataset.prepare(\"valid\", col_set=[\"feature\", \"label\"], data_key=DataHandlerLP.DK_L)\n        self.logger.info(f\"Train samples: {len(dl_train)}\")\n        self.logger.info(f\"Valid samples: {len(dl_valid)}\")\n        if dl_train.empty or dl_valid.empty:\n            raise ValueError(\"Empty data from dataset, please check your dataset config.\")\n\n        if reweighter is None:\n            wl_train = np.ones(len(dl_train))\n            wl_valid = np.ones(len(dl_valid))\n        elif isinstance(reweighter, Reweighter):\n            wl_train = reweighter.reweight(dl_train)\n            wl_valid = reweighter.reweight(dl_valid)\n        else:\n            raise ValueError(\"Unsupported reweighter type.\")\n\n        # Preprocess for data.  To align to Dataset Interface for DataLoader\n        if ists:\n            dl_train.config(fillna_type=\"ffill+bfill\")  # process nan brought by dataloader\n            dl_valid.config(fillna_type=\"ffill+bfill\")  # process nan brought by dataloader\n        else:\n            # If it is a tabular, we convert the dataframe to numpy to be indexable by DataLoader\n            dl_train = dl_train.values\n            dl_valid = dl_valid.values\n\n        train_loader = DataLoader(\n            ConcatDataset(dl_train, wl_train),\n            batch_size=self.batch_size,\n            shuffle=True,\n            num_workers=self.n_jobs,\n            drop_last=True,\n        )\n        valid_loader = DataLoader(","sourceCodeStart":240,"sourceCodeEnd":276,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_general_nn.py#L240-L276","documentation":"Raised in DNNModelPytorch.fit when the `reweighter` argument is neither None nor an instance of qlib.model.base.Reweighter. Sample weights are mandatory internally (the DataLoader wraps data with a weight array), so the model must resolve reweighter to a concrete weight vector; anything else (a function, dict, ndarray) is rejected.","triggerScenarios":"Calling fit(dataset, reweighter=some_function) or passing a custom object that mimics Reweighter but does not subclass it. Note the check is isinstance-based, so duck typing fails even if the object has a .reweight method.","commonSituations":"Implementing a custom sample-weighting scheme (e.g. weighting by volatility or recency) as a lambda/function instead of a Reweighter subclass; passing sklearn-style sample_weight arrays directly.","solutions":["Wrap your weighting logic in qlib.model.base.Reweighter: subclass it and implement reweight(df) returning a per-row weight array aligned with the DataFrame index.","Pass reweighter=None if you do not need sample weights (uniform weights are used automatically)."],"exampleFix":"# before\ndef my_w(df):\n    return (df.index.year - 2000).values\nmodel.fit(dataset, reweighter=my_w)  # ValueError\n\n# after\nfrom qlib.model.base import Reweighter\nclass YearReweighter(Reweighter):\n    def reweight(self, df):\n        return (df.index.get_level_values(0).year - 2000).values\nmodel.fit(dataset, reweighter=YearReweighter())","handlingStrategy":"type-guard","validationCode":"from qlib.model.base import Reweighter\nassert reweighter is None or isinstance(reweighter, Reweighter), \"reweighter must be None or a qlib.model.base.Reweighter instance\"","typeGuard":"from qlib.model.base import Reweighter\n\ndef is_valid_reweighter(r) -> bool:\n    return r is None or isinstance(r, Reweighter)","tryCatchPattern":"try:\n    model.fit(dataset, reweighter=reweighter)\nexcept ValueError as e:\n    if \"Unsupported reweighter type\" in str(e):\n        model.fit(dataset)  # retry without reweighting\n    else:\n        raise","preventionTips":["Implement custom sample weighting as a Reweighter subclass, never as a bare function or array.","isinstance is enforced — duck typing is not enough; always subclass qlib.model.base.Reweighter."],"tags":["qlib","reweighter","type-check","api-misuse"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}