Skip to content

Instantly share code, notes, and snippets.

@Vindaar
Last active December 4, 2020 16:23
Show Gist options
  • Save Vindaar/cf77804ae592268714bab0730b976d2c to your computer and use it in GitHub Desktop.
Save Vindaar/cf77804ae592268714bab0730b976d2c to your computer and use it in GitHub Desktop.
import sequtils
type
CpuStorage*[T] = ref CpuStorageObj[T]
CpuStorageObj[T] = object
size*: int
raw_buffer*: ptr UncheckedArray[T]
Tensor[T] = object
buf*: CpuStorage[T]
proc `=destroy`[T](s: var CpuStorageObj[T]) =
s.raw_buffer.deallocShared()
s.size = 0
s.raw_buffer = nil
proc `=`[T](a: var CpuStorageObj[T]; b: CpuStorageObj[T]) {.error.}
proc allocCpuStorage[T](s: var CpuStorage[T], size: int) =
new(s)
s.raw_buffer = cast[ptr UncheckedArray[T]](allocShared0(sizeof(T) * size))
s.size = size
proc newTensor[T](size: int): Tensor[T] =
allocCpuStorage(result.buf, size)
proc `[]`[T](t: Tensor[T], idx: int): T = t.buf.raw_buffer[idx]
proc `[]=`[T](t: Tensor[T], idx: int, val: T) = t.buf.raw_buffer[idx] = val
func size[T](t: Tensor[T]): int = t.buf.size
proc toTensor[T](s: seq[T]): Tensor[T] =
result = newTensor[T](s.len)
for i, x in s:
result[i] = x
type
Column* = ref object # works if normal object
fCol: Tensor[float]
proc asType*(t: Tensor[float]): Tensor[float] {.noInit.} = # works if `noInit` removed
result = t
proc toColumn*(t: Tensor[float]): Column =
result = Column(fCol: t.asType())
## works with regular contruction of ref object:
#result = new Column
#result.fCol = t.asType()
proc theBug =
# works with `32551` on my machine
#let occ = toSeq(0 .. 32251).mapIt(it.float).toTensor()
# replacing toSeq.mapIt by a for loop makes it go away
# broken with `32252`
let occ = toSeq(0 .. 32252).mapIt(it.float).toTensor()
let c = toColumn occ
theBug()
#[
Results in
Hint: /tmp/testbug [Exec]
Traceback (most recent call last)
/tmp/testbug.nim(57) testbug
/tmp/testbug.nim(55) theBug
/tmp/testbug.nim(44) toColumn
/tmp/testbug.nim(40) asType
/home/basti/src/nim/nim_git_repo/lib/system/arc.nim(198) nimDecRefIsLast
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Error: execution of an external program failed: '/tmp/testbug '
- make `Column` a normal object and it works
- explicitly use `result = new Column` syntax in `toColumn` and it works
- replace `toSeq.mapIt` by for loop and it works
- make `toSeq` upper range 1 smaller and it works
- remove `noInit` on `asType` and it works
]#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment