[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add size assert, refactor #3

Merged
merged 4 commits into from
Jul 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions tensor1d.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,26 @@ void *malloc_check(size_t size, const char *file, int line) {
// ----------------------------------------------------------------------------
// utils

inline int ceil_div(int a, int b) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree on getting rid of inline if it causes issues. I didn't realize inline was contentious and has sharp edges.

int ceil_div(int a, int b) {
// integer division that rounds up, i.e. ceil(a / b)
return (a + b - 1) / b;
}

int min(int a, int b) {
return (a < b) ? a : b;
}

int max(int a, int b) {
return (a > b) ? a : b;
}

// ----------------------------------------------------------------------------
// Storage: simple array of floats, defensive on index access, reference-counted
// The reference counting allows multiple Tensors sharing the same Storage.
// similar to torch.Storage

Storage* storage_new(int size) {
assert(size >= 0);
Storage* storage = mallocCheck(sizeof(Storage));
storage->data = mallocCheck(size * sizeof(float));
storage->data_size = size;
Expand Down Expand Up @@ -157,11 +166,9 @@ Tensor* tensor_slice(Tensor* t, int start, int end, int step) {
// 1) handle negative indices by wrapping around
if (start < 0) { start = t->size + start; }
if (end < 0) { end = t->size + end; }
// 2) handle out-of-bounds indices: clip to 0 and t->size
if (start < 0) { start = 0; }
if (end < 0) { end = 0; }
if (start > t->size) { start = t->size; }
if (end > t->size) { end = t->size; }
// 2) handle out-of-bounds indices: clip to [0, t->size] range
start = min(max(start, 0), t->size);
end = min(max(end, 0), t->size);
// 3) handle step
if (step == 0) {
fprintf(stderr, "ValueError: slice step cannot be zero\n");
Expand Down