|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Linq; |
| 8 | +using TorchSharp; |
| 9 | +using static TorchSharp.torch; |
| 10 | +using static TorchSharp.torch.nn; |
| 11 | + |
| 12 | +namespace Microsoft.ML.TorchSharp.AutoFormerV2 |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Anchor boxes are a set of predefined bounding boxes of a certain height and width, whose location and size can be adjusted by the regression head of model. |
| 16 | + /// </summary> |
| 17 | + public class Anchors : Module<Tensor, Tensor> |
| 18 | + { |
| 19 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:private field names not in _camelCase format", Justification = "Need to match TorchSharp.")] |
| 20 | + private readonly int[] pyramidLevels; |
| 21 | + |
| 22 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:private field names not in _camelCase format", Justification = "Need to match TorchSharp.")] |
| 23 | + private readonly int[] strides; |
| 24 | + |
| 25 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:private field names not in _camelCase format", Justification = "Need to match TorchSharp.")] |
| 26 | + private readonly int[] sizes; |
| 27 | + |
| 28 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:private field names not in _camelCase format", Justification = "Need to match TorchSharp.")] |
| 29 | + private readonly double[] ratios; |
| 30 | + |
| 31 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:private field names not in _camelCase format", Justification = "Need to match TorchSharp.")] |
| 32 | + private readonly double[] scales; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Initializes a new instance of the <see cref="Anchors"/> class. |
| 36 | + /// </summary> |
| 37 | + /// <param name="pyramidLevels">Pyramid levels.</param> |
| 38 | + /// <param name="strides">Strides between adjacent bboxes.</param> |
| 39 | + /// <param name="sizes">Different sizes for bboxes.</param> |
| 40 | + /// <param name="ratios">Different ratios for height/width.</param> |
| 41 | + /// <param name="scales">Scale size of bboxes.</param> |
| 42 | + public Anchors(int[] pyramidLevels = null, int[] strides = null, int[] sizes = null, double[] ratios = null, double[] scales = null) |
| 43 | + : base(nameof(Anchors)) |
| 44 | + { |
| 45 | + this.pyramidLevels = pyramidLevels != null ? pyramidLevels : new int[] { 3, 4, 5, 6, 7 }; |
| 46 | + this.strides = strides != null ? strides : this.pyramidLevels.Select(x => (int)Math.Pow(2, x)).ToArray(); |
| 47 | + this.sizes = sizes != null ? sizes : this.pyramidLevels.Select(x => (int)Math.Pow(2, x + 2)).ToArray(); |
| 48 | + this.ratios = ratios != null ? ratios : new double[] { 0.5, 1, 2 }; |
| 49 | + this.scales = scales != null ? scales : new double[] { Math.Pow(2, 0), Math.Pow(2, 1.0 / 3.0), Math.Pow(2, 2.0 / 3.0) }; |
| 50 | + } |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Generate anchors for an image. |
| 54 | + /// </summary> |
| 55 | + /// <param name="image">Image in Tensor format.</param> |
| 56 | + /// <returns>All anchors.</returns> |
| 57 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")] |
| 58 | + public override Tensor forward(Tensor image) |
| 59 | + { |
| 60 | + using (var scope = torch.NewDisposeScope()) |
| 61 | + { |
| 62 | + var imageShape = torch.tensor(image.shape.AsSpan().Slice(2).ToArray()); |
| 63 | + |
| 64 | + // compute anchors over all pyramid levels |
| 65 | + var allAnchors = torch.zeros(new long[] { 0, 4 }, dtype: torch.float32); |
| 66 | + |
| 67 | + for (int idx = 0; idx < this.pyramidLevels.Length; ++idx) |
| 68 | + { |
| 69 | + var x = this.pyramidLevels[idx]; |
| 70 | + var shape = ((imageShape + Math.Pow(2, x) - 1) / Math.Pow(2, x)).to_type(torch.int32); |
| 71 | + var anchors = GenerateAnchors( |
| 72 | + baseSize: this.sizes[idx], |
| 73 | + ratios: this.ratios, |
| 74 | + scales: this.scales); |
| 75 | + var shiftedAnchors = Shift(shape, this.strides[idx], anchors); |
| 76 | + allAnchors = torch.cat(new List<Tensor>() { allAnchors, shiftedAnchors }, dim: 0); |
| 77 | + } |
| 78 | + |
| 79 | + var output = allAnchors.unsqueeze(dim: 0); |
| 80 | + output = output.to(image.device); |
| 81 | + |
| 82 | + return output.MoveToOuterDisposeScope(); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /// <summary> |
| 87 | + /// Generate a set of anchors given size, ratios and scales. |
| 88 | + /// </summary> |
| 89 | + /// <param name="baseSize">Base size for width and height.</param> |
| 90 | + /// <param name="ratios">Ratios for height/width.</param> |
| 91 | + /// <param name="scales">Scales to resize base size.</param> |
| 92 | + /// <returns>A set of anchors.</returns> |
| 93 | + private static Tensor GenerateAnchors(int baseSize = 16, double[] ratios = null, double[] scales = null) |
| 94 | + { |
| 95 | + using (var anchorsScope = torch.NewDisposeScope()) |
| 96 | + { |
| 97 | + ratios ??= new double[] { 0.5, 1, 2 }; |
| 98 | + scales ??= new double[] { Math.Pow(2, 0), Math.Pow(2, 1.0 / 3.0), Math.Pow(2, 2.0 / 3.0) }; |
| 99 | + |
| 100 | + var numAnchors = ratios.Length * scales.Length; |
| 101 | + |
| 102 | + // initialize output anchors |
| 103 | + var anchors = torch.zeros(new long[] { numAnchors, 4 }, dtype: torch.float32); |
| 104 | + |
| 105 | + // scale base_size |
| 106 | + anchors[.., 2..] = baseSize * torch.tile(scales, new long[] { 2, ratios.Length }).transpose(1, 0); |
| 107 | + |
| 108 | + // compute areas of anchors |
| 109 | + var areas = torch.mul(anchors[.., 2], anchors[.., 3]); |
| 110 | + |
| 111 | + // correct for ratios |
| 112 | + anchors[.., 2] = torch.sqrt(areas / torch.repeat_interleave(ratios, new long[] { scales.Length })); |
| 113 | + anchors[.., 3] = torch.mul(anchors[.., 2], torch.repeat_interleave(ratios, new long[] { scales.Length })); |
| 114 | + |
| 115 | + // transform from (x_ctr, y_ctr, w, h) -> (x1, y1, x2, y2) |
| 116 | + anchors[.., torch.TensorIndex.Tensor(torch.tensor(new long[] { 0, 2 }, dtype: torch.int64))] -= torch.tile(anchors[.., 2] * 0.5, new long[] { 2, 1 }).T; |
| 117 | + anchors[.., torch.TensorIndex.Tensor(torch.tensor(new long[] { 1, 3 }, dtype: torch.int64))] -= torch.tile(anchors[.., 3] * 0.5, new long[] { 2, 1 }).T; |
| 118 | + |
| 119 | + return anchors.MoveToOuterDisposeScope(); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + /// <summary> |
| 124 | + /// Duplicate and distribute anchors to different positions give border of positions and stride between positions. |
| 125 | + /// </summary> |
| 126 | + /// <param name="shape">Border to distribute anchors.</param> |
| 127 | + /// <param name="stride">Stride between adjacent anchors.</param> |
| 128 | + /// <param name="anchors">Anchors to distribute.</param> |
| 129 | + /// <returns>The shifted anchors.</returns> |
| 130 | + private static Tensor Shift(Tensor shape, int stride, Tensor anchors) |
| 131 | + { |
| 132 | + using (var anchorsScope = torch.NewDisposeScope()) |
| 133 | + { |
| 134 | + Tensor shiftX = (torch.arange(start: 0, stop: (int)shape[1]) + 0.5) * stride; |
| 135 | + Tensor shiftY = (torch.arange(start: 0, stop: (int)shape[0]) + 0.5) * stride; |
| 136 | + |
| 137 | + var shiftXExpand = torch.repeat_interleave(shiftX.reshape(new long[] { shiftX.shape[0], 1 }), shiftY.shape[0], dim: 1); |
| 138 | + shiftXExpand = shiftXExpand.transpose(0, 1).reshape(-1); |
| 139 | + var shiftYExpand = torch.repeat_interleave(shiftY, shiftX.shape[0]); |
| 140 | + |
| 141 | + List<Tensor> tensors = new List<Tensor> { shiftXExpand, shiftYExpand, shiftXExpand, shiftYExpand }; |
| 142 | + var shifts = torch.vstack(tensors).transpose(0, 1); |
| 143 | + |
| 144 | + var a = anchors.shape[0]; |
| 145 | + var k = shifts.shape[0]; |
| 146 | + var allAnchors = anchors.reshape(new long[] { 1, a, 4 }) + shifts.reshape(new long[] { 1, k, 4 }).transpose(0, 1); |
| 147 | + allAnchors = allAnchors.reshape(new long[] { k * a, 4 }); |
| 148 | + |
| 149 | + return allAnchors.MoveToOuterDisposeScope(); |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | +} |
0 commit comments