|
| 1 | +# |
| 2 | +# Copyright (c) 2023, NVIDIA CORPORATION. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | + |
| 17 | +from typing import Dict, Optional, Union |
| 18 | + |
| 19 | +import torch |
| 20 | + |
| 21 | + |
| 22 | +@torch.jit.script |
| 23 | +class Sequence: |
| 24 | + """ |
| 25 | + A PyTorch scriptable class representing a sequence of tabular data. |
| 26 | +
|
| 27 | + Attributes: |
| 28 | + lengths (Dict[str, torch.Tensor]): A dictionary mapping the feature names to their |
| 29 | + corresponding sequence lengths. |
| 30 | + masks (Dict[str, torch.Tensor]): A dictionary mapping the feature names to their |
| 31 | + corresponding masks. Default is an empty dictionary. |
| 32 | +
|
| 33 | + Examples: |
| 34 | + >>> lengths = {'feature1': torch.tensor([4, 5]), 'feature2': torch.tensor([3, 7])} |
| 35 | + >>> masks = {'feature1': torch.tensor([[1, 0], [1, 1]]), 'feature2': torch.tensor([[1, 1], [1, 0]])} # noqa: E501 |
| 36 | + >>> seq = Sequence(lengths, masks) |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + lengths: Union[torch.Tensor, Dict[str, torch.Tensor]], |
| 42 | + masks: Optional[Union[torch.Tensor, Dict[str, torch.Tensor]]] = None, |
| 43 | + ): |
| 44 | + if isinstance(lengths, torch.Tensor): |
| 45 | + _lengths = {"default": lengths} |
| 46 | + elif torch.jit.isinstance(lengths, Dict[str, torch.Tensor]): |
| 47 | + _lengths = lengths |
| 48 | + else: |
| 49 | + raise ValueError("Lengths must be a tensor or a dictionary of tensors") |
| 50 | + self.lengths: Dict[str, torch.Tensor] = _lengths |
| 51 | + |
| 52 | + if masks is None: |
| 53 | + _masks = {} |
| 54 | + elif isinstance(masks, torch.Tensor): |
| 55 | + _masks = {"default": masks} |
| 56 | + elif torch.jit.isinstance(masks, Dict[str, torch.Tensor]): |
| 57 | + _masks = masks |
| 58 | + else: |
| 59 | + raise ValueError("Masks must be a tensor or a dictionary of tensors") |
| 60 | + self.masks: Dict[str, torch.Tensor] = _masks |
| 61 | + |
| 62 | + def __contains__(self, name: str) -> bool: |
| 63 | + return name in self.lengths |
| 64 | + |
| 65 | + def length(self, name: str = "default") -> torch.Tensor: |
| 66 | + if name in self.lengths: |
| 67 | + return self.lengths[name] |
| 68 | + |
| 69 | + raise ValueError("Batch has multiple lengths, please specify a feature name") |
| 70 | + |
| 71 | + def mask(self, name: str = "default") -> torch.Tensor: |
| 72 | + if name in self.masks: |
| 73 | + return self.masks[name] |
| 74 | + |
| 75 | + raise ValueError("Batch has multiple masks, please specify a feature name") |
| 76 | + |
| 77 | + |
| 78 | +@torch.jit.script |
| 79 | +class Batch: |
| 80 | + """ |
| 81 | + A PyTorch scriptable class representing a batch of data. |
| 82 | +
|
| 83 | + Attributes: |
| 84 | + features (Dict[str, torch.Tensor]): A dictionary mapping feature names to their |
| 85 | + corresponding feature values. |
| 86 | + targets (Dict[str, torch.Tensor]): A dictionary mapping target names to their |
| 87 | + corresponding target values. Default is an empty dictionary. |
| 88 | + sequences (Optional[Sequence]): An optional instance of the Sequence class |
| 89 | + representing sequence lengths and masks for the batch. |
| 90 | +
|
| 91 | + Examples: |
| 92 | + >>> features = {'feature1': torch.tensor([1, 2]), 'feature2': torch.tensor([3, 4])} |
| 93 | + >>> targets = {'target1': torch.tensor([0, 1])} |
| 94 | + >>> batch = Batch(features, targets) |
| 95 | + """ |
| 96 | + |
| 97 | + def __init__( |
| 98 | + self, |
| 99 | + features: Union[torch.Tensor, Dict[str, torch.Tensor]], |
| 100 | + targets: Optional[Union[torch.Tensor, Dict[str, torch.Tensor]]] = None, |
| 101 | + sequences: Optional[Sequence] = None, |
| 102 | + ): |
| 103 | + default_key = "default" |
| 104 | + |
| 105 | + if isinstance(features, torch.Tensor): |
| 106 | + _features = {default_key: features} |
| 107 | + elif torch.jit.isinstance(features, Dict[str, torch.Tensor]): |
| 108 | + _features = features |
| 109 | + else: |
| 110 | + raise ValueError("Features must be a tensor or a dictionary of tensors") |
| 111 | + |
| 112 | + self.features: Dict[str, torch.Tensor] = _features |
| 113 | + |
| 114 | + if isinstance(targets, torch.Tensor): |
| 115 | + targets = {default_key: targets} |
| 116 | + |
| 117 | + if targets is None: |
| 118 | + _targets = {} |
| 119 | + elif torch.jit.isinstance(targets, Dict[str, torch.Tensor]): |
| 120 | + _targets = targets |
| 121 | + else: |
| 122 | + raise ValueError("Targets must be a tensor or a dictionary of tensors") |
| 123 | + self.targets: Dict[str, torch.Tensor] = _targets |
| 124 | + self.sequences: Optional[Sequence] = sequences |
| 125 | + |
| 126 | + def replace( |
| 127 | + self, |
| 128 | + features: Optional[Dict[str, torch.Tensor]] = None, |
| 129 | + targets: Optional[Dict[str, torch.Tensor]] = None, |
| 130 | + sequences: Optional[Sequence] = None, |
| 131 | + ) -> "Batch": |
| 132 | + """ |
| 133 | + Create a new `Batch` instance, replacing specified attributes with new values. |
| 134 | +
|
| 135 | + Parameters |
| 136 | + ---------- |
| 137 | + features : Optional[Dict[str, torch.Tensor]] |
| 138 | + A dictionary of tensors representing the features of the batch. Default is None. |
| 139 | + targets : Optional[Dict[str, torch.Tensor]] |
| 140 | + A dictionary of tensors representing the targets of the batch. Default is None. |
| 141 | + sequences : Optional[Sequence] |
| 142 | + An instance of the Sequence class representing sequence lengths and masks for the |
| 143 | + batch. Default is None. |
| 144 | +
|
| 145 | + Returns |
| 146 | + ------- |
| 147 | + Batch |
| 148 | + A new Batch object with replaced attributes. |
| 149 | + """ |
| 150 | + |
| 151 | + return Batch( |
| 152 | + features=features if features is not None else self.features, |
| 153 | + targets=targets if targets is not None else self.targets, |
| 154 | + sequences=sequences if sequences is not None else self.sequences, |
| 155 | + ) |
| 156 | + |
| 157 | + def feature(self, name: str = "default") -> torch.Tensor: |
| 158 | + """Retrieve a feature tensor from the batch by its name. |
| 159 | +
|
| 160 | + Parameters |
| 161 | + ---------- |
| 162 | + name : str |
| 163 | + The name of the feature tensor to return. Default is "default". |
| 164 | +
|
| 165 | + Returns |
| 166 | + ------- |
| 167 | + torch.Tensor |
| 168 | + The feature tensor of the specified name. |
| 169 | +
|
| 170 | + Raises |
| 171 | + ------ |
| 172 | + ValueError |
| 173 | + If the specified name does not exist in the features attribute. |
| 174 | + """ |
| 175 | + |
| 176 | + if name in self.features: |
| 177 | + return self.features[name] |
| 178 | + |
| 179 | + raise ValueError("Batch has multiple features, please specify a feature name") |
| 180 | + |
| 181 | + def target(self, name: str = "default") -> torch.Tensor: |
| 182 | + """Retrieve a target tensor from the batch by its name. |
| 183 | +
|
| 184 | + Parameters |
| 185 | + ---------- |
| 186 | + name : str |
| 187 | + The name of the target tensor to return. Default is "default". |
| 188 | +
|
| 189 | + Returns |
| 190 | + ------- |
| 191 | + torch.Tensor |
| 192 | + The target tensor of the specified name. |
| 193 | +
|
| 194 | + Raises |
| 195 | + ------ |
| 196 | + ValueError |
| 197 | + If the specified name does not exist in the targets attribute. |
| 198 | + """ |
| 199 | + |
| 200 | + if name in self.targets: |
| 201 | + return self.targets[name] |
| 202 | + |
| 203 | + raise ValueError("Batch has multiple target, please specify a target name") |
| 204 | + |
| 205 | + def __bool__(self) -> bool: |
| 206 | + return bool(self.features) |
0 commit comments