The topic of the assignment is implement a parallel k-NN program. The method of parallelization should be threads. You may use C++ (recommended) or C, or any mix of the two. Other languages may be allowed. If you are interested, you may contact the instructor.
The k-NN problem is to find the k nearest neighbors of a given query point. When used in data science, the assumption is that the neighbors of a point will have similar characteristics to the query point. For example, suppose you are trying to predict the favorite movie of a person. It would be reasonable to assume that if Joe is similar to Mary in other ways, they might have the same favorite movie.
The k-NN problem is commonly solved using k-d trees. A k-d tree is like a binary search tree, except that each node represents a split along a different dimension. That is, each node corresponds to a particular dimension, and the split is along that dimension. Thus, each node can be thought of as representing a hyperplane. Data points to the negative side of the hyperplane are in the left subtree, while data points to the positive side of the hyperplane are in the right subtree. The dimensions typically alternate in a round-robin fashion as the depth increases. Thus, the root node (zeroeth level) might split along the x dimension, first level nodes along the y dimension, second level nodes along the z dimension, third level nodes along the x dimension, etc.
As with binary search trees, balance is an issue. If the tree is unbalanced, search times will increase. k-d trees can be balanced by choosing the median point (in the appropriate dimension) as the split value. The median point can be found exactly by sorting the points, or can be approximated by randomly choosing a subset of the points and sorting those.
Searching a k-d tree is relatively straightforward. Given a query point, the tree is first descended as if inserting the point. Once a leaf node is reached, the tree is followed upward. At each node, the distance to the hyperplane is compared against the current nearest neighbors. If needed, the other branch is then descended.
Requirements
The program take four arguments on the command line.
./k-nn n_cores training_file query_file result_file
The number of cores is that have been allocated for this execution is given by n_cores. You may use this to better determine how many threads to create. (You can also query this programmatically by calling sched_getaffinity(). The training points are given in training_file. The queries are given in query_file. The results should be written to result_file. To prevent overwriting an important file, you may wish to confirm that it does not already exist. To minimize I/O processing time, the files are in binary (native byte order).
Training File Format
The header of the training file is as below.
Field Size in Bytes Data Type Notes
File type string 8 Array of chars, padded out with zeroes The type string for training files is "TRAINING". This is exactly 8 chars, so there is no 0 byte at the end.
Training file ID 8 Unsigned, 64-bit integer A randomly-generated number that can be used to uniquely identify files.
Number of points 8 Unsigned, 64-bit integer
Number of dimensions 8 Unsigned 64-bit integer
Assistant
After the header are the points, given as a sequence of 32-bit floating-point numbers.
The training file ID is a opaque, unique ID. It purpose is to help correlate training files with result files.
Query File Format
The header of the query file is:
Field Size in Bytes Data Type Notes
File type string 8 Array of chars, padded out with zeroes The type string for query files is "QUERY".
Query file ID 8 Unsigned, 64-bit integer A randomly-generated number that uniquely identifies files.
Number of queries 8 Unsigned, 64-bit integer
Number of dimensions 8 Unsigned 64-bit integer
Number of neighbors to return for each query 8 Unsigned 64-bit integer
After the header are the queries, given as a sequence of 32-bit floating-point numbers.
The query file ID is a opaque, unique ID. It purpose is to help correlate query files with result files.
Results File Format
The header of the results file is:
Field Size in Bytes Data Type Notes
File type string 8 Array of chars, padded out with zeroes The type string for query files is "RESULT".
Training file ID 8 Unsigned, 64-bit integer The ID of the training file used to generate this results file.
Query file ID 8 Unsigned, 64-bit integer The ID of the query file used to generate this results file.
Result file ID 8 Unsigned, 64-bit integer A randomly-generated number that uniquely identifies this file.
Number of queries 8 Unsigned, 64-bit integer
Number of dimensions 8 Unsigned 64-bit integer
Number of neighbors returned for each query 8 Unsigned 64-bit integer
After the header are the results, given as a sequence of 32-bit floating-point numbers.
The training file ID must match the ID given in the training file. The query file ID must match the ID given in the query file. The result file ID will be generated by your program. Generate a random number by reading from /dev/urandom.
Timing Outputs
The program must print the total time (wall clock) to build the tree and the total time to execute the queries.
Implementing a parallel k-Nearest Neighbors (k-NN) program using threads in C++ is a multifaceted task that involves several key components:
Reading and Parsing Binary Files: Understand and correctly parse the binary formats for training, query, and result files.
Building a k-d Tree: Implement an efficient k-d tree for organizing the training data.
Parallelizing Tree Construction and Query Processing: Use multithreading to utilize multiple cores effectively.
Executing Queries: Perform k-NN searches using the k-d tree.
Writing Results: Output the results in the specified binary format.
Timing Execution: Accurately measure and report the time taken for tree construction and query processing.
Below is a comprehensive guide to help you implement this assignment, complete with code snippets and explanations.
Table of Contents
Prerequisites
Project Structure
Reading Binary Files
Implementing the k-d Tree
Parallelizing with Threads
Executing k-NN Queries
Writing the Results File
Timing the Execution
Complete Example
Best Practices and Optimization
Prerequisites
C++ Knowledge: Familiarity with C++11 or later (for threading support).
Understanding of k-d Trees and k-NN: Basic knowledge to implement the algorithm.
Multithreading Concepts: Understanding how to create and manage threads.
Binary File I/O: Experience with reading and writing binary data in C++.
Project Structure
Organizing your code effectively will make the implementation smoother. Here's a suggested structure:
Building the Tree: The buildRecursive function sorts the points based on the current splitting dimension and selects the median as the current node, ensuring the tree is balanced.
k-NN Search: The kNNRecursive function traverses the tree to find the k nearest neighbors using a max-heap (priority_queue). It backtracks when necessary to consider other branches.
Parallelizing with Threads
To utilize multiple cores, you can parallelize both the tree construction and the query processing. However, k-d tree construction is typically recursive and hard to parallelize effectively. Thus, focus primarily on parallelizing the query processing.
We'll use a thread pool pattern to manage threads efficiently.
cpp
// utils.h
#ifndef UTILS_H
#define UTILS_H
#include <vector>
#include <thread>
#include <functional>
class ThreadPool {
public:
ThreadPool(size_t num_threads);
~ThreadPool();
// Submit a task to the pool
void enqueue(std::function<void()> task);
// Wait for all tasks to complete
void wait();
private:
std::vector<std::thread> workers;
std::vector<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
#endif // UTILS_H
Thread Pool: Manages a fixed number of threads that execute tasks from a queue.
Enqueue Tasks: Allows submitting tasks to be executed by the thread pool.
Wait: Waits until all tasks are completed.
Executing k-NN Queries
Parallelize the processing of queries by distributing them across multiple threads.
cpp
Explanation:
Command-Line Arguments: The program expects four arguments: number of cores, training file, query file, and result file.
File Existence Check: Ensures the result file doesn't already exist to prevent accidental overwrites.
Reading Training Data:
Opens the training file.
Reads the header and validates the file type.
Reads all training points into memory.
Building the k-d Tree:
Measures the time taken to build the tree.
Constructs the KDTree object with the training points.
Reading Query Data:
Opens the query file.
Reads the header and validates the file type.
Reads all query points into memory.
Checks for dimensional consistency between training and query data.
Processing Queries in Parallel:
Initializes a ThreadPool with the specified number of cores.
Dispatches each query to the thread pool.
Each thread performs the k-NN search and stores the flattened neighbor coordinates.
Uses a mutex to safely write results to the shared all_results vector.
Writing the Result File:
Constructs the result header, generating a unique ID from /dev/urandom.
Writes the header and all results to the result file in binary format.
Timing Outputs:
Prints the time taken to build the k-d tree and execute all queries.
Writing the Results File
The results file must adhere to the specified binary format. Each result for a query consists of the concatenated dimensions of its k nearest neighbors.
cpp
// Included in file_io.cpp as part of the FileIO::writeResultFile function
void FileIO::writeResultFile(const std::string &filename, const ResultHeader &header, const std::vector<std::vector<float>> &results) {
std::ofstream ofs(filename, std::ios::binary);
if(!ofs.is_open()) throw std::runtime_error("Cannot open result file for writing");
// Write header
ofs.write(header.file_type, 8);
ofs.write(reinterpret_cast<const char*>(&header.training_file_id), 8);
ofs.write(reinterpret_cast<const char*>(&header.query_file_id), 8);
ofs.write(reinterpret_cast<const char*>(&header.result_file_id), 8);
ofs.write(reinterpret_cast<const char*>(&header.num_queries), 8);
ofs.write(reinterpret_cast<const char*>(&header.num_dimensions), 8);
ofs.write(reinterpret_cast<const char*>(&header.k_neighbors), 8);
// Write results
for(const auto &neighbors : results) {
ofs.write(reinterpret_cast<const char*>(neighbors.data()), sizeof(float) * neighbors.size());
}
}
Notes:
Result Header: Must reflect the correct metadata, including matching training and query file IDs.
Result Data: For each query, write k * num_dimensions 32-bit floating-point numbers representing the neighbor points.
Timing the Execution
Accurate timing is crucial for performance analysis and must only measure the tree construction and query processing times.
cpp
// Timing is already integrated in the main function
auto build_start = std::chrono::high_resolution_clock::now();
// Build tree
auto build_end = std::chrono::high_resolution_clock::now();
double build_time = std::chrono::duration<double>(build_end - build_start).count();
auto query_start = std::chrono::high_resolution_clock::now();
// Execute queries
auto query_end = std::chrono::high_resolution_clock::now();
double query_time = std::chrono::duration<double>(query_end - query_start).count();
// Output timing
std::cout << "Time to build the tree: " << build_time << " seconds\n";
std::cout << "Time to execute the queries: " << query_time << " seconds\n";
Separation of Concerns: Timing for tree building and query processing are measured separately for clarity.
Complete Example
For clarity, here's an all-in-one example combining the components. Note that in practice, you should organize the code into separate files as previously outlined.
cpp
// main.cpp
#include "file_io.h"
#include "kd_tree.h"
#include "utils.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <chrono>
#include <random>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
// Same generate_random_id function as before
int main(int argc, char* argv[]) {
// ... [Same as the main function detailed earlier]
}
Build Instructions:
Assuming you have all .cpp and .h files correctly set up, here’s a simple Makefile:
Consider using median-of-medians for better performance in selecting medians.
In high-dimensional data, k-d trees might not perform optimally. Explore alternative data structures if necessary.
Thread Safety:
Minimize the use of mutexes by partitioning the work such that each thread works on a distinct subset of queries.
Alternatively, preallocate the all_results vector and have each thread write to its assigned indices without locking.
Memory Management:
Ensure that large datasets fit into memory. If not, consider out-of-core algorithms.
I/O Optimization:
Read the entire file into memory if feasible to reduce disk I/O overhead.
Use memory-mapped files (mmap) for potentially faster access.
Load Balancing:
Distribute queries evenly among threads to prevent some threads from being idle while others are overloaded.
Profiling and Benchmarking:
Use profiling tools to identify bottlenecks.
Experiment with different numbers of threads to find the optimal count based on the number of available cores and the workload.
Error Handling:
Implement comprehensive error handling, especially for file I/O and thread operations.
Scalability:
Design the program to scale with the number of cores and handle large datasets efficiently.
Conclusion
Implementing a parallel k-NN program using threads in C++ involves careful consideration of data structures, multithreading paradigms, and performance optimizations. By following the outlined steps and best practices, you can build an efficient and robust solution that meets the assignment's requirements. Remember to test your program thoroughly with various datasets to ensure correctness and performance.
If you encounter specific issues or have further questions, feel free to ask!