{"record":{"id":"a42352141fa7b24e","repo":"hankcs/HanLP","slug":"alpha-must-be-float-list-of-float-or-torch-float","errorCode":null,"errorMessage":"alpha must be float, list of float, or torch.FloatTensor, {} provided.","messagePattern":"alpha must be float, list of float, or torch\\.FloatTensor, (.+?) provided\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"hanlp/components/parsers/ud/udify_util.py","lineNumber":226,"sourceCode":"        if isinstance(alpha, (float, int)):\n\n            # shape : (2,)\n            alpha_factor = torch.tensor(\n                [1.0 - float(alpha), float(alpha)], dtype=weights.dtype, device=weights.device\n            )\n\n        elif isinstance(alpha, (list, numpy.ndarray, torch.Tensor)):\n\n            # shape : (c,)\n            alpha_factor = torch.tensor(alpha, dtype=weights.dtype, device=weights.device)\n\n            if not alpha_factor.size():\n                # shape : (1,)\n                alpha_factor = alpha_factor.view(1)\n                # shape : (2,)\n                alpha_factor = torch.cat([1 - alpha_factor, alpha_factor])\n        else:\n            raise TypeError(\n                (\"alpha must be float, list of float, or torch.FloatTensor, {} provided.\").format(\n                    type(alpha)\n                )\n            )\n        # shape : (batch, max_len)\n        alpha_factor = torch.gather(alpha_factor, dim=0, index=targets_flat.view(-1)).view(\n            *targets.size()\n        )\n        weights = weights * alpha_factor\n\n    if label_smoothing is not None and label_smoothing > 0.0:\n        num_classes = logits.size(-1)\n        smoothing_value = label_smoothing / num_classes\n        # Fill all the correct indices with 1 - smoothing value.\n        one_hot_targets = torch.zeros_like(log_probs_flat).scatter_(\n            -1, targets_flat, 1.0 - label_smoothing\n        )\n        smoothed_targets = one_hot_targets + smoothing_value","sourceCodeStart":208,"sourceCodeEnd":244,"githubUrl":"https://github.com/hankcs/HanLP/blob/ddb1299bddff079e447af52ec12549c50636bfa8/hanlp/components/parsers/ud/udify_util.py#L208-L244","documentation":"In udify's focal-loss code path, `alpha` balances class weights and must be a float, a list of floats, or a torch.FloatTensor. When alpha is another type (e.g. an int, numpy scalar, string, or None handled elsewhere), the branch resolution fails and a TypeError is raised showing the offending type.","triggerScenarios":"Calling sequence_cross_entropy_with_logits with alpha=1 (int), alpha=np.float32(0.25), or alpha=\"0.25\"; alpha=None with gamma set goes down a different path, but any non-float/list/tensor type lands here.","commonSituations":"Passing integer alpha (like alpha=1) instead of 1.0; passing numpy types from a data pipeline; copying focal-loss hyperparameters from papers that use strings.","solutions":["Pass a Python float (alpha=0.25), a list of floats, or a torch.FloatTensor","Convert numpy scalars: alpha=float(alpha)","If you want plain cross entropy, set gamma=0 and alpha=None instead of a non-float alpha placeholder"],"exampleFix":"# before\nloss = sequence_cross_entropy_with_logits(logits, targets, weights, gamma=2.0, alpha=1)\n# after\nloss = sequence_cross_entropy_with_logits(logits, targets, weights, gamma=2.0, alpha=1.0)","handlingStrategy":"type-guard","validationCode":"assert alpha is None or isinstance(alpha, (float, int)) and not isinstance(alpha, bool) or isinstance(alpha, (list, torch.FloatTensor)), f'bad alpha type {type(alpha)}'\nif isinstance(alpha, int) and not isinstance(alpha, bool):\n    alpha = float(alpha)","typeGuard":"def is_valid_alpha(a) -> bool:\n    return a is None or isinstance(a, float) or (\n        isinstance(a, list) and all(isinstance(x, float) for x in a)\n    ) or isinstance(a, torch.FloatTensor)","tryCatchPattern":"try:\n    loss = sequence_cross_entropy_with_logits(..., alpha=alpha)\nexcept TypeError as e:\n    if 'alpha must be float' in str(e):\n        alpha = float(alpha)  # retry with normalized type\n        loss = sequence_cross_entropy_with_logits(..., alpha=alpha)\n    else:\n        raise","preventionTips":["Normalize numeric hyperparameters to float at config-load time","Never pass ints/numpy scalars straight into typed loss APIs"],"tags":["python","pytorch","focal-loss","type-error"],"backgroundTag":"invalid-argument-type","analyzedSha":"ddb1299bddff079e447af52ec12549c50636bfa8","analyzedAt":"2026-08-27T03:36:54.287Z","schemaVersion":2},"datasetVersion":"2026-08-27T08:17:20.692Z"}