del tensor free memory
This commit is contained in:
parent
b56ed81cd7
commit
6701179c22
14 changed files with 61 additions and 14 deletions
|
|
@ -16,28 +16,27 @@ extern "C" {
|
|||
fprintf(stderr, "Memory allocation failed\n");
|
||||
exit(1);
|
||||
}
|
||||
tensor->data = data;
|
||||
tensor->shape = shape;
|
||||
tensor->ndim = ndim;
|
||||
|
||||
tensor->device = (char*)malloc(strlen(device) + 1);
|
||||
if (device != NULL) {
|
||||
strcpy(tensor->device, device);
|
||||
} else {
|
||||
fprintf(stderr, "Memory allocation failed\n");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
tensor->size = 1;
|
||||
for (int i = 0; i < ndim; i++) {
|
||||
tensor->size *= shape[i];
|
||||
}
|
||||
|
||||
tensor->device = strdup(device);
|
||||
tensor->strides = (int*)malloc(ndim * sizeof(int));
|
||||
if (tensor->strides == NULL) {
|
||||
tensor->shape = (int*)malloc(ndim * sizeof(int));
|
||||
tensor->data = (float*)malloc(tensor->size * sizeof(float));
|
||||
|
||||
if (tensor->device == NULL || tensor->strides == NULL || tensor->shape == NULL || tensor->data == NULL) {
|
||||
fprintf(stderr, "Memory allocation failed\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
memcpy(tensor->shape, shape, tensor->ndim * sizeof(int));
|
||||
strcpy(tensor->device, device);
|
||||
memcpy(tensor->data, data, tensor->size * sizeof(float));
|
||||
|
||||
int stride = 1;
|
||||
for (int i = ndim - 1; i >= 0; i--) {
|
||||
tensor->strides[i] = stride;
|
||||
|
|
@ -47,6 +46,43 @@ extern "C" {
|
|||
return tensor;
|
||||
}
|
||||
|
||||
void delete_tensor(Tensor* tensor) {
|
||||
if (tensor != NULL) {
|
||||
|
||||
if (tensor->strides != NULL) {
|
||||
free(tensor->strides);
|
||||
tensor->strides = NULL;
|
||||
}
|
||||
|
||||
if (tensor->shape != NULL) {
|
||||
free(tensor->shape);
|
||||
tensor->shape = NULL;
|
||||
}
|
||||
|
||||
if (tensor->data != NULL) {
|
||||
if (strcmp(tensor->device, "cpu") == 0) {
|
||||
free(tensor->data);
|
||||
} else {
|
||||
free_cuda(tensor->data);
|
||||
}
|
||||
tensor->data = NULL;
|
||||
}
|
||||
|
||||
if (tensor->device != NULL) {
|
||||
free(tensor->device);
|
||||
tensor->device = NULL;
|
||||
}
|
||||
|
||||
if (tensor->strides != NULL) {
|
||||
free(tensor->strides);
|
||||
tensor->strides = NULL;
|
||||
}
|
||||
|
||||
free(tensor);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
float get_item(Tensor* tensor, int* indices) {
|
||||
int index = 0;
|
||||
for (int i = 0; i < tensor->ndim; i++) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue