M
Modular•3mo ago
franchesoni

print breaks code

the following isn't catched by the linter but breaks, what am I doing wrong?
from python import Python, PythonObject
from memory import memcpy

alias S: Int = 256
alias S2: Int = S*S
alias CRASH = True

def main():
np = Python.import_module('numpy')
pylogits = np.ones((130, 256, 256))
total_size = Int(pylogits.size)

# now we have the data in memory
data = UnsafePointer[Scalar[DType.float32]].alloc(total_size)
memcpy(data, pylogits.__array_interface__['data'][0].unsafe_get_as_pointer[DType.float32](), total_size)

# mojomain(data, total_size)
var masks = UnsafePointer[Scalar[DType.bool]].alloc(total_size)
for channel in range(total_size / S2):
offset = S2 * channel
for ind in range(S2):
masks[ind + offset] = True if data[ind+offset] > 0.5 else False
if CRASH:
print(masks[offset + S])

print('great!') # never get here

from python import Python, PythonObject
from memory import memcpy

alias S: Int = 256
alias S2: Int = S*S
alias CRASH = True

def main():
np = Python.import_module('numpy')
pylogits = np.ones((130, 256, 256))
total_size = Int(pylogits.size)

# now we have the data in memory
data = UnsafePointer[Scalar[DType.float32]].alloc(total_size)
memcpy(data, pylogits.__array_interface__['data'][0].unsafe_get_as_pointer[DType.float32](), total_size)

# mojomain(data, total_size)
var masks = UnsafePointer[Scalar[DType.bool]].alloc(total_size)
for channel in range(total_size / S2):
offset = S2 * channel
for ind in range(S2):
masks[ind + offset] = True if data[ind+offset] > 0.5 else False
if CRASH:
print(masks[offset + S])

print('great!') # never get here

8 Replies
DobyDabaDu
DobyDabaDu•3mo ago
Put this after memcpy:
_ = pylogits.__array_interface__['data'][0].__index__()
_ = pylogits.__array_interface__['data'][0].__index__()
sora
sora•3mo ago
BTW, use this in memcpy: ref
arr.ctypes.data.unsafe_get_as_pointer[type]()
arr.ctypes.data.unsafe_get_as_pointer[type]()
franchesoni
franchesoniOP•3mo ago
this one breaks, it seems to have undefined type
sora
sora•3mo ago
Sorry i wasn't being very clear. You are suppose to change arr and type to own need
franchesoni
franchesoniOP•3mo ago
my bad, hadn't noticed the [type] placeholder. It crashes later, but it's still nicer 🙂 thanks this piece of black magic works. Why? 😮
sora
sora•3mo ago
This should do the trick as well. Basically, it tells the compiler to not free pylogits before the memcpy.
_ = pylogits
_ = pylogits
We have something called ASAP destruction
franchesoni
franchesoniOP•3mo ago
oh sure that makes sense! thanks 🤗
Want results from more Discord servers?
Add your server