1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
|
package tensor
import (
"runtime"
)
// MultIterator is an iterator that iterates over multiple tensors, including masked tensors.
// It utilizes the *AP of a Tensor to determine what the next index is.
// This data structure is similar to Numpy's flatiter, with some standard Go based restrictions of course
// (such as, not allowing negative indices)
type MultIterator struct {
*AP // Uses AP of the largest tensor in list
fit0 *FlatIterator //largest fit in fitArr (by AP total size)
mask []bool
numMasked int
lastIndexArr []int
shape Shape
whichBlock []int
fitArr []*FlatIterator
strides []int
size int
done bool
reverse bool
}
func genIterator(m map[int]int, strides []int, idx int) (int, bool) {
key := hashIntArray(strides)
f, ok := m[key]
if !ok {
m[key] = idx
return idx, ok
}
return f, ok
}
// NewMultIterator creates a new MultIterator from a list of APs
func NewMultIterator(aps ...*AP) *MultIterator {
nit := len(aps)
if nit < 1 {
return nil
}
for _, ap := range aps {
if ap == nil {
panic("ap is nil") //TODO: Probably remove this panic
}
}
var maxDims int
var maxShape = aps[0].shape
for i := range aps {
if aps[i].Dims() >= maxDims {
maxDims = aps[i].Dims()
if aps[i].Size() > maxShape.TotalSize() {
maxShape = aps[i].shape
}
}
}
it := new(MultIterator)
it.whichBlock = BorrowInts(nit)
it.lastIndexArr = BorrowInts(nit)
it.strides = BorrowInts(nit * maxDims)
shape := BorrowInts(len(maxShape))
copy(shape, maxShape)
it.shape = shape
for _, ap := range aps {
_, err := BroadcastStrides(shape, ap.shape, it.strides[:maxDims], ap.strides)
if err != nil {
panic("can not broadcast strides")
}
}
for i := range it.strides {
it.strides[i] = 0
}
it.fitArr = make([]*FlatIterator, nit)
//TODO: Convert this make to Borrow perhaps?
m := make(map[int]int)
nBlocks := 0
offset := 0
for i, ap := range aps {
f, ok := genIterator(m, ap.strides, nBlocks)
if !ok {
offset = nBlocks * maxDims
apStrides, _ := BroadcastStrides(shape, ap.shape, it.strides[offset:offset+maxDims], ap.strides)
copy(it.strides[offset:offset+maxDims], apStrides)
ReturnInts(apStrides) // Borrowed in BroadcastStrides but returned here - dangerous pattern?
nBlocks++
}
ap2 := MakeAP(it.shape[:maxDims], it.strides[offset:offset+maxDims], ap.o, ap.Δ)
it.whichBlock[i] = f
it.fitArr[nBlocks-1] = newFlatIterator(&ap2)
}
it.fitArr = it.fitArr[:nBlocks]
it.strides = it.strides[:nBlocks*maxDims]
// fill 0s with 1s
for i := range it.strides {
if it.strides[i] == 0 {
it.strides[i] = 1
}
}
it.fit0 = it.fitArr[0]
for _, f := range it.fitArr {
if it.fit0.size < f.size {
it.fit0 = f
it.AP = f.AP
}
}
return it
}
// MultIteratorFromDense creates a new MultIterator from a list of dense tensors
func MultIteratorFromDense(tts ...DenseTensor) *MultIterator {
aps := make([]*AP, len(tts))
hasMask := BorrowBools(len(tts))
defer ReturnBools(hasMask)
var masked = false
numMasked := 0
for i, tt := range tts {
aps[i] = tt.Info()
if mt, ok := tt.(MaskedTensor); ok {
hasMask[i] = mt.IsMasked()
}
masked = masked || hasMask[i]
if hasMask[i] {
numMasked++
}
}
it := NewMultIterator(aps...)
runtime.SetFinalizer(it, destroyIterator)
if masked {
// create new mask slice if more than tensor is masked
if numMasked > 1 {
it.mask = BorrowBools(it.shape.TotalSize())
memsetBools(it.mask, false)
for i, err := it.Start(); err == nil; i, err = it.Next() {
for j, k := range it.lastIndexArr {
if hasMask[j] {
it.mask[i] = it.mask[i] || tts[j].(MaskedTensor).Mask()[k]
}
}
}
}
}
it.numMasked = numMasked
return it
}
// destroyMultIterator returns any borrowed objects back to pool
func destroyMultIterator(it *MultIterator) {
if cap(it.whichBlock) > 0 {
ReturnInts(it.whichBlock)
it.whichBlock = nil
}
if cap(it.lastIndexArr) > 0 {
ReturnInts(it.lastIndexArr)
it.lastIndexArr = nil
}
if cap(it.strides) > 0 {
ReturnInts(it.strides)
it.strides = nil
}
if it.numMasked > 1 {
if cap(it.mask) > 0 {
ReturnBools(it.mask)
it.mask = nil
}
}
}
// SetReverse initializes iterator to run backward
func (it *MultIterator) SetReverse() {
for _, f := range it.fitArr {
f.SetReverse()
}
}
// SetForward initializes iterator to run forward
func (it *MultIterator) SetForward() {
for _, f := range it.fitArr {
f.SetForward()
}
}
//Start begins iteration
func (it *MultIterator) Start() (int, error) {
it.Reset()
return it.Next()
}
//Done checks whether iterators are done
func (it *MultIterator) Done() bool {
for _, f := range it.fitArr {
if !f.done {
it.done = false
return false
}
}
it.done = true
return true
}
// Next returns the index of the next coordinate
func (it *MultIterator) Next() (int, error) {
if it.done {
return -1, noopError{}
}
it.done = false
for _, f := range it.fitArr {
if _, err := f.Next(); err != nil {
return -1, err
}
it.done = it.done || f.done
}
for i, j := range it.whichBlock {
it.lastIndexArr[i] = it.fitArr[j].lastIndex
}
return it.fit0.lastIndex, nil
}
func (it *MultIterator) NextValidity() (int, bool, error) {
i, err := it.Next()
if err != nil {
return i, false, err
}
if len(it.mask) == 0 {
return i, true, err
}
return i, it.mask[i], err
}
// NextValid returns the index of the next valid coordinate
func (it *MultIterator) NextValid() (int, int, error) {
var invalid = true
var count int
var mult = 1
if it.reverse {
mult = -1
}
for invalid {
if it.done {
for i, j := range it.whichBlock {
it.lastIndexArr[i] = it.fitArr[j].lastIndex
}
return -1, 0, noopError{}
}
for _, f := range it.fitArr {
f.Next()
it.done = it.done || f.done
}
count++
invalid = !it.mask[it.fit0.lastIndex]
}
return it.fit0.lastIndex, mult * count, nil
}
// NextInvalid returns the index of the next invalid coordinate
func (it *MultIterator) NextInvalid() (int, int, error) {
var valid = true
var count = 0
var mult = 1
if it.reverse {
mult = -1
}
for valid {
if it.done {
for i, j := range it.whichBlock {
it.lastIndexArr[i] = it.fitArr[j].lastIndex
}
return -1, 0, noopError{}
}
for _, f := range it.fitArr {
f.Next()
it.done = it.done || f.done
}
count++
valid = !it.mask[it.fit0.lastIndex]
}
return it.fit0.lastIndex, mult * count, nil
}
// Coord returns the next coordinate.
// When Next() is called, the coordinates are updated AFTER the Next() returned.
// See example for more details.
func (it *MultIterator) Coord() []int {
return it.fit0.track
}
// Reset resets the iterator state.
func (it *MultIterator) Reset() {
for _, f := range it.fitArr {
f.Reset()
}
for i, j := range it.whichBlock {
it.lastIndexArr[i] = it.fitArr[j].lastIndex
}
it.done = false
}
// LastIndex returns index of requested iterator
func (it *MultIterator) LastIndex(j int) int {
return it.lastIndexArr[j]
}
/*
// Chan returns a channel of ints. This is useful for iterating multiple Tensors at the same time.
func (it *FlatIterator) Chan() (retVal chan int) {
retVal = make(chan int)
go func() {
for next, err := it.Next(); err == nil; next, err = it.Next() {
retVal <- next
}
close(retVal)
}()
return
}
*/
|