|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +# |
| 18 | + |
| 19 | +from typing import Optional |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +import torch |
| 23 | +from jaxtyping import Bool, Float, Int |
| 24 | + |
| 25 | +numpy_to_torch_dtype_dict = { |
| 26 | + bool: torch.bool, |
| 27 | + np.uint8: torch.uint8, |
| 28 | + np.int8: torch.int8, |
| 29 | + np.int16: torch.int16, |
| 30 | + np.int32: torch.int32, |
| 31 | + np.int64: torch.int64, |
| 32 | + np.float16: torch.float16, |
| 33 | + np.float32: torch.float32, |
| 34 | + np.float64: torch.float64, |
| 35 | + np.complex64: torch.complex64, |
| 36 | + np.complex128: torch.complex128, |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def packed_attention_mask( |
| 41 | + sample_id: Int[torch.Tensor, "*batch seq_len"], |
| 42 | +) -> Bool[torch.Tensor, "*batch seq_len seq_len"]: |
| 43 | + sample_id = sample_id.unsqueeze(-1) |
| 44 | + attention_mask = sample_id.eq(sample_id.mT) |
| 45 | + return attention_mask |
| 46 | + |
| 47 | + |
| 48 | +def packed_causal_attention_mask( |
| 49 | + sample_id: Int[torch.Tensor, "*batch seq_len"], |
| 50 | + time_id: Int[torch.Tensor, "*batch seq_len"], |
| 51 | +) -> Bool[torch.Tensor, "*batch seq_len seq_len"]: |
| 52 | + attention_mask = packed_attention_mask(sample_id) |
| 53 | + expanded_id1 = time_id.unsqueeze(-2) |
| 54 | + expanded_id2 = time_id.unsqueeze(-1) |
| 55 | + compare_res = expanded_id1 <= expanded_id2 |
| 56 | + attention_mask = attention_mask * compare_res |
| 57 | + return attention_mask |
| 58 | + |
| 59 | + |
| 60 | +def mask_fill( |
| 61 | + tensor: Float[torch.Tensor, "*batch dim"], |
| 62 | + mask: Bool[torch.Tensor, "*batch"], |
| 63 | + value: Float[torch.Tensor, "dim"], |
| 64 | +) -> Float[torch.Tensor, "*batch dim"]: |
| 65 | + mask = mask.unsqueeze(-1) |
| 66 | + return tensor * ~mask + value * mask |
| 67 | + |
| 68 | + |
| 69 | +def safe_div( |
| 70 | + numer: torch.Tensor, |
| 71 | + denom: torch.Tensor, |
| 72 | +) -> torch.Tensor: |
| 73 | + return numer / torch.where( |
| 74 | + denom == 0, |
| 75 | + 1.0, |
| 76 | + denom, |
| 77 | + ) |
| 78 | + |
| 79 | + |
| 80 | +def size_to_mask( |
| 81 | + max_size: int, |
| 82 | + sizes: Int[torch.Tensor, "*batch"], |
| 83 | +) -> Bool[torch.Tensor, "*batch max_size"]: |
| 84 | + mask = torch.arange(max_size, device=sizes.device) |
| 85 | + return torch.lt(mask, sizes.unsqueeze(-1)) |
| 86 | + |
| 87 | + |
| 88 | +def fixed_size( |
| 89 | + value: Float[torch.Tensor, "*batch max_size"], |
| 90 | +) -> Int[torch.Tensor, "*batch"]: |
| 91 | + sizes = torch.ones_like(value[..., 0], dtype=torch.long) * value.shape[-1] |
| 92 | + return sizes |
| 93 | + |
| 94 | + |
| 95 | +def sized_mean( |
| 96 | + value: Float[torch.Tensor, "*batch max_size"], |
| 97 | + sizes: Optional[Int[torch.Tensor, "*batch"]], |
| 98 | + dim: Optional[int | tuple[int, ...]] = None, |
| 99 | + keepdim: bool = False, |
| 100 | + size_keepdim: bool = False, |
| 101 | + correction: int = 0, |
| 102 | +) -> Float[torch.Tensor, "..."]: |
| 103 | + value = value * size_to_mask(value.shape[-1], sizes) |
| 104 | + div_val = safe_div( |
| 105 | + value.sum(dim=-1).sum(dim, keepdim=keepdim), |
| 106 | + torch.clamp(sizes.sum(dim, keepdim=keepdim) - correction, min=0), |
| 107 | + ) |
| 108 | + if size_keepdim: |
| 109 | + div_val = div_val.unsqueeze(-1) |
| 110 | + return div_val |
| 111 | + |
| 112 | + |
| 113 | +def masked_mean( |
| 114 | + value: Float[torch.Tensor, "..."], |
| 115 | + mask: Bool[torch.Tensor, "..."], |
| 116 | + dim: Optional[int | tuple[int, ...]] = None, |
| 117 | + keepdim: bool = False, |
| 118 | + correction: int = 0, |
| 119 | +) -> Float[torch.Tensor, "..."]: |
| 120 | + return safe_div( |
| 121 | + (value * mask).sum(dim=dim, keepdim=keepdim), |
| 122 | + torch.clamp(mask.float().sum(dim, keepdim=keepdim) - correction, min=0), |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +def unsqueeze_trailing_dims(x: torch.Tensor, shape: torch.Size) -> torch.Tensor: |
| 127 | + if x.ndim > len(shape) or x.shape != shape[: x.ndim]: |
| 128 | + raise ValueError |
| 129 | + dim = (...,) + (None,) * (len(shape) - x.ndim) |
| 130 | + return x[dim] |
0 commit comments