typedef enum ccml_buff {
// default buffer
CCML_BUFF_NONE,
// only exist as intermediary scalar values in compute kernels
CCML_BUFF_INTR,
// allocated buffer for constant tensors
CCML_BUFF_CNST,
// dedicated buffer for tensors whose data is loaded from memory
CCML_BUFF_LOAD,
// dedicated buffer for tensors whose data is saved into memory
CCML_BUFF_SAVE
} ccml_buff;
static ccml_tensor * ccml_new_tensor_4d(ccml_type type, int ne0, int ne1, int ne2, int ne3,
bool has_grad) {
int shape[CCML_DIMS_MAX] = {ne0, ne1, ne2, ne3};
static ccml_tensor * ccml_reshape(ccml_tensor * tensor, int shape[CCML_DIMS_MAX]) {
int size = ccml_tensor_size(tensor);
int new_size = shape[0] * shape[1] * shape[2] * shape[3];
assert(size == new_size && "reshaped and source tensor must have the same size");
static const char * ccml_oper_to_string(ccml_oper oper) {
switch (oper) {
case CCML_OPER_NONE: return "";
case CCML_OPER_LOG: return "log";
case CCML_OPER_EXP: return "exp";
case CCML_OPER_SIN: return "sin";
case CCML_OPER_REC: return "1/";
case CCML_OPER_SQRT: return "sqrt";
case CCML_OPER_ADD: return "+";
case CCML_OPER_MUL: return "*";
case CCML_OPER_RESHAPE: return "";
case CCML_OPER_PERMUTE: return "";
default: assert(false && "invalid conversion of type to string");
}
}
static const char * ccml_type_to_string(ccml_type type) {
switch (type) {
case CCML_TYPE_FP16: return "fp16";
case CCML_TYPE_FP32: return "fp32";
case CCML_TYPE_FP64: return "fp64";
default: assert(false && "unknown variant of ccml_type");
}
}
// super unsafe i think?
static void ccml_find_and_replace(char * string, const char * needle, const char * replacement) {
char * haystack = string;
char * result = haystack;
while ((result = strstr(result, needle)) != NULL) {
size_t position = result - haystack;
size_t length = strlen(needle);
memmove(haystack + position + strlen(replacement), haystack + position + length,
strlen(haystack + position + length) + 1);
memcpy(haystack + position, replacement, strlen(replacement));
result += strlen(replacement);
}
}
// both reduction and broadcasting index functions look terrible, there has to be a cleaner
// and concise way to express this
// in this loop create gradient tensors corresponding to each tensor
// that requires gradient tracking, and set their buffers to the correct
// option respectively (because, for example, a intermediary tensor w/o
// a buffer also needs an intermediary gradient tensor w/o a buffer)
ccml_tensor * queue[CCML_NODE_MAX] = {NULL};
int queue_start = 0;
int queue_end = 0;
queue[queue_end++] = root;
while (queue_end != queue_start) {
ccml_tensor * tensor = queue[queue_start++];
if (tensor->has_grad == true) {
// processing node here
// declaring partials d(tensor)/d(tensor->src[0]) and
// d(tensor)/d(tensor->src[1])
ccml_tensor * partial_0 = NULL;
ccml_tensor * partial_1 = NULL;
int shape[CCML_DIMS_MAX] = {1, 1, 1, 1};
ccml_tensor * one = ccml_const(tensor->type, shape, 1.0f);
ccml_tensor * two = ccml_const(tensor->type, shape, 1.0f);
// calculating partials
switch (tensor->oper) {
case CCML_OPER_NONE:
break;
case CCML_OPER_LOG:
partial_0 = ccml_rec(tensor->src[0]);
break;
case CCML_OPER_EXP:
partial_0 = ccml_exp(tensor->src[0]);
break;
case CCML_OPER_SIN:
partial_0 = ccml_cos(tensor->src[0]);
break;
case CCML_OPER_REC:
partial_0 = ccml_neg(ccml_rec(ccml_square(tensor->src[0])));
break;
case CCML_OPER_SQRT:
partial_0 = ccml_rec(ccml_mul(two, ccml_sqrt(tensor->src[0])));
break;
case CCML_OPER_ADD:
partial_0 = one; partial_1 = one;
break;
case CCML_OPER_MUL:
partial_0 = tensor->src[1]; partial_1 = tensor->src[0];
break;
case CCML_OPER_RESHAPE:
case CCML_OPER_PERMUTE:
partial_0 = one;
break;
case CCML_OPER_SUM_REDUCE:
partial_0 = one;
break;
default: assert(false && "unknown variant of ccml_oper");
}
// multiplying tensor->grad by partials and adding them to
// the gradients of the tensor's children (we have to do a
// mini DFS traversal w/ ccml_graph_forward() since the gradient
// calculation forms a mini sub-graph that needs to be tra-
// versed separately)
if (tensor->src[0] != NULL) {
tensor->src[0]->grad = ccml_add(ccml_mul(tensor->grad, partial_0), NULL);
ccml_graph_forward(graph, tensor->src[0]->grad, &graph->n_nodes);
}
if (tensor->src[1] != NULL) {
tensor->src[1]->grad = ccml_add(ccml_mul(tensor->grad, partial_1), NULL);
ccml_graph_forward(graph, tensor->src[1]->grad, &graph->n_nodes);
}
// finished processing node and adding children
if (tensor->src[0] != NULL) {
queue[queue_end++] = tensor->src[0];
}
if (tensor->src[1] != NULL) {
queue[queue_end++] = tensor->src[1];
}
}
}
static void ccml_graph_free(ccml_graph * graph) {
for (int i = 0; i < graph->n_nodes; i++) {
ccml_tensor * tensor = graph->nodes[i];
// only freeing when tensor isn't of type reshape/permute, because those tensors
// just use their children's data pointer, so we avoid a double free this way :)
if (tensor->oper != CCML_OPER_RESHAPE && tensor->oper != CCML_OPER_PERMUTE) {
free(tensor->data);
}
free(tensor);
}
free(graph);
// adding includes and kernel function signature to the
// kernel string
int offset = snprintf(kernel_string + strlen(kernel_string), size - strlen(graph->ir),
"#include <cuda_fp16.h>\n\n__global__ void ccml_kernel(");
str += offset;
// adding kernel input parameters to the kernel string
int n_kernel_parameters = 0;
int largest_tensor = 1;
for (int i = 0; i < graph->n_nodes; i++) {
ccml_tensor * tensor = graph->nodes[i];
int tensor_size = ccml_tensor_size(tensor);
if (tensor_size > largest_tensor)
largest_tensor = tensor_size;
if (ccml_has_buffer(tensor) && ccml_tensor_size(tensor) != 1) {
if (n_kernel_parameters == 0) {
str += snprintf(str, size - (str - kernel_string),
"%s * data_%d", ccml_type_to_string(tensor->type), i);
n_kernel_parameters++;
} else {
str += snprintf(str, size - (str - kernel_string),
", %s * data_%d", ccml_type_to_string(tensor->type), i);
n_kernel_parameters++;
}
}
}
str += snprintf(str, size - (str - kernel_string),
") {\n\tint idx = blockDim.x * blockIdx.x + threadIdx.x;\n"
"\tif (idx < %d) return;\n\n",
largest_tensor);
// prepending kernel_string to graph->ir
memmove(kernel_string + strlen(kernel_string), graph->ir, strlen(graph->ir) + 1);
// cuda specific type substitution (i.e. fp16 to __half and fp32 to float)
// adding offset so that fp16 from the include header name doesn't get
// replaced
ccml_find_and_replace(kernel_string + offset, "fp16", "__half");
ccml_find_and_replace(kernel_string + offset, "fp32", "float");
ccml_find_and_replace(kernel_string + offset, "fp64", "double");
// adding the closing braces/brackets :)
snprintf(kernel_string + strlen(kernel_string), size - strlen(graph->ir), "}");
return kernel_string;
}
#endif
The provided code is a comprehensive and intricate example of a computational graph framework designed for tensor operations with potential CUDA integration. It includes definition and manipulation of tensors, operations on tensors, and a system to generate intermediary representation (IR) that potentially converts to CUDA kernel code. Below is an analysis highlighting potential issues along with improvements.
Potential Issues and Improvements:
1. Memory Leaks and Allocation Checks:
Whenever malloc is called (e.g., in ccml_new_tensor_impl, ccml_const, ccml_new_hashmap, etc.), there should be a corresponding free in an appropriate location to avoid memory leaks. Ensure all allocated resources are properly released when they are no longer needed.
There are no checks for the return value of malloc. If malloc fails due to insufficient memory, it returns NULL, which can lead to dereferencing a NULL pointer and subsequent crash. Before using the allocated memory, check if the pointer is not NULL.
2. ccml_tensor Initialization:
The initialization of the ccml_tensor structure within the ccml_new_tensor_impl function does not need explicit commenting (/*.type =*/). Modern C compilers and IDEs are capable of showing member name assignments without comments, and if the structure changes, these comments become misleading or incorrect.
3. Code Repetition:
The ccml_new_tensor_1d, ccml_new_tensor_2d, ccml_new_tensor_3d, and ccml_new_tensor_4d functions have repetitive logic and differ mainly in how they set the shape array. Consider a utility function that handles the common logic to reduce code repetition.
4. Hazardous String Operations:
Functions like ccml_reduction_index and ccml_broadcasting_index allocate memory for strings and return them, expecting the caller to manage this memory. This can easily lead to memory leaks if not handled correctly. Furthermore, functions like ccml_find_and_replace operate directly on string contents, which can lead to buffer overflow if replacements result in a string exceeding the original's size.
5. Error Handling and Assertions:
Extensive use of assert is observed for error handling, which might not be suitable for production code. Assertions are disabled if NDEBUG is defined, potentially bypassing important checks. Consider using proper error handling mechanisms that remain active in release builds.
6. CUDE-Specific Logic in ccml_parser_cuda:
ccml_parser_cuda function contains CUDA-specific logic mixed with generic tensor operations. Consider maintaining a clear separation between generic computational graph logic and backend-specific code generation to enhance modularity and maintainability.
7. Potential for Optimization:
Evaluate opportunities for optimizing tensor operations, especially those that can leverage SIMD (Single Instruction, Multiple Data) instructions or GPU acceleration properly.
For operations like broadcasting and reduction, more efficient indexing or parallel strategies can significantly improve performance.
8. Thread Safety and Parallel Execution:
The current implementation does not address thread safety or parallel execution explicitly. If targeting GPUs or multi-core CPUs, consider thread safety, especially when mutating shared structures or when dealing with operations that can be parallelized.
Conclusion:
The code represents a solid foundation for a tensor manipulation library with potential GPU acceleration. Addressing these issues and considering improvements for memory management, error handling, and parallel execution can enhance robustness, performance, and maintainability.
Certainly! To address the concerns related to memory allocation, particularly ensuring all allocated memory is properly freed and adding null checks after using malloc, I'll provide the fixed code for specific functions that directly involve memory allocations.
For brevity, I'll focus on the key areas where these issues apply. You should apply similar fixes for any other allocations within the codebase.
1. Memory Leak Fixes and Allocation Checks:
Modified ccml_const
static ccml_tensor * ccml_const(ccml_type type, int shape[CCML_DIMS_MAX], float value) {
ccml_tensor * result = ccml_new_tensor_impl(type, shape);
if (!result) return NULL; // Allocation check
result->type = CCML_TYPE_FP32;
result->buff = CCML_BUFF_CNST;
int size = shape[0] * shape[1] * shape[2] * shape[3];
result->data = malloc(size * sizeof(float));
if (!result->data) { // Allocation check
free(result); // Free previously allocated memory to prevent leaks
return NULL;
}
for (int i = 0; i < size; i++) {
((float *)result->data)[i] = value; // Corrected data access
}
return result;
}
Considering the need to free allocated resources properly, it's advisable to add a cleanup or destruction function for structures like ccml_tensor and ccml_hashmap to encapsulate memory deallocation logic.
static void ccml_free_tensor(ccml_tensor *tensor) {
if (!tensor) return;
if (tensor->data) free(tensor->data);
free(tensor);
}
static void ccml_free_hashmap(ccml_hashmap *map) {
if (!map) return;
if (map->entries) free(map->entries);
free(map);
}
Usage Example
When you're done with a ccml_hashmap instance:
ccml_hashmap *map = ccml_new_hashmap();
// Use the map for operations
ccml_free_hashmap(map); // Cleanup when done.
This should handle the memory leak and allocation check concerns for the points mentioned. Make sure to integrate the cleanup functions appropriately in your codebase, ensuring that every resource allocation has a corresponding deallocation pathway.
Remember, managing memory manually in C requires diligent tracking of all allocations and deallocations to prevent leaks and undefined behavior.
To effectively and safely manage memory in your codebase, any new function definitions (like the modified versions of ccml_const and ccml_new_hashmap, as well as the new ccml_free_tensor and ccml_free_hashmap cleanup functions) should be placed within their respective logical grouping in your source files. Specifically, here's how you can organize these:
Where to Place Modified and New Functions:
Modified Functions (ccml_const and ccml_new_hashmap):
Replace the existing implementations of ccml_const and ccml_new_hashmap in your source file with the corrected versions provided. These adjustments typically reside in the same source code file where they were initially defined.
New Cleanup Functions:
The cleanup functions (ccml_free_tensor and ccml_free_hashmap) should be introduced into your codebase in a location that logically groups them with related functionality. If your codebase segregates tensor operations and memory management into specific files or sections, these cleanup functions should be placed accordingly.
For example, if you have a file dedicated to tensor operations, the ccml_free_tensor function should go there. Similarly, if there's a part of your code that deals with hashmap operations, ccml_free_hashmap should be included in that location.
If you don't have such segregation, you can place these functions near the end of your source file where the primary operations for ccml_tensor and ccml_hashmap are defined.
Integration with the Rest of the Code:
You should integrate calls to ccml_free_tensor and ccml_free_hashmap wherever tensors and hashmaps are no longer needed or before any return that precedes a function end to prevent memory leaks. This could be within any cleanup or error handling sections of your code.
For any newly created tensor or hashmap that fails (due to subsequent operations failing or program logic dictating an early return), make sure to call these cleanup functions to release the allocated resources correctly.
Example Integration:
After defining ccml_free_tensor(tensor);, you would call it like:
ccml_tensor *tensor = ccml_const(...);
if (someCondition) {
ccml_free_tensor(tensor);
return ERROR_CODE;
}
// Continue using tensor
And similar for hashmaps:
ccml_hashmap *map = ccml_new_hashmap();
if (!map) {
// Handle error
return ERROR_CODE;
}
// Use map
if (someCondition) {
ccml_free_hashmap(map);
return ERROR_CODE;
}
// Continue using map
Final Note:
Ensure that these integrations and modifications are thoroughly tested to prevent any unintended behaviors, such as double frees or use-after-free errors, especially in complex logic flows and error handling paths.