### Setup Performance Comparison Simulators Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Downloads and prepares various memory simulators for performance comparison. ```bash cd perf_comparison mkdir simulators cd simulators git clone https://github.com/umd-memsys/DRAMSim2.git # DRAMSim2 git clone https://github.com/umd-memsys/DRAMsim3 # DRAMSim3 wget http://www.cs.utah.edu/~rajeev/usimm-v1.3.tar.gz # USIMM v1.3 tar xvzf ./usimm-v1.3.tar.gz git clone https://github.com/CMU-SAFARI/ramulator.git # Ramulator 1.0 mv ramulator ramulatorv1 git clone https://github.com/CMU-SAFARI/ramulator2.git # Ramulator 2.0 mv ramulator2 ramulatorv2 ``` -------------------------------- ### Basic DDR4 Configuration Example Source: https://context7.com/cmu-safari/ramulator2/llms.txt A sample YAML configuration file for a basic DDR4 memory system setup. This includes frontend, memory system, DRAM, controller, and address mapping configurations. ```yaml Frontend: impl: SimpleO3 clock_ratio: 8 num_expected_insts: 500000 traces: - example_inst.trace Translation: impl: RandomTranslation max_addr: 2147483648 MemorySystem: impl: GenericDRAM clock_ratio: 3 DRAM: impl: DDR4 org: preset: DDR4_8Gb_x8 channel: 1 rank: 2 timing: preset: DDR4_2400R Controller: impl: Generic Scheduler: impl: FRFCFS RefreshManager: impl: AllBank RowPolicy: impl: ClosedRowPolicy cap: 4 plugins: AddrMapper: impl: RoBaRaCoCh ``` -------------------------------- ### Automate Experiments with Python Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Example script for sweeping timing constraints by passing configuration strings to the simulator. ```python import os import yaml # YAML parsing provided with the PyYAML package baseline_config_file = "./example_config.yaml" nRCD_list = [10, 15, 20, 25] base_config = None with open(base_config_file, 'r') as f: base_config = yaml.safe_load(f) for nRCD in nRCD_list: config["MemorySystem"]["DRAM"]["timing"]["nRCD"] = nRCD cmds = ["./ramulator2", str(config)] # Run the command with e.g., os.system(), subprocess.run(), ... ``` -------------------------------- ### Configure Ramulator 2.0 in gem5 Script Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Example of instantiating the Ramulator 2.0 memory controller within a gem5 configuration script. ```python import m5 from m5.objects import * system = System() system.mem_ctrl = Ramulator2() system.mem_ctrl.config_path = ".yaml" # Don't forget to specify GEM5 as the implementation of the frontend interface! # Continue your configuration of gem5 ... ``` -------------------------------- ### Implement an Example Interface Class in C++ Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Provides a concrete implementation 'ExampleImpl' for the 'ExampleIfce' interface. It inherits from both 'ExampleIfce' and 'Implementation', and uses the 'RAMULATOR_REGISTER_IMPLEMENTATION' macro for registration. The 'foo()' function is overridden to print 'Bar!'. ```cpp // example_impl.cpp #include // An implementation should always include the header of the interface that it is implementating #include "example_interface.h" namespace Ramulator { // An implementation class should always inherit from *both* the interface it is implementating, and the "Implementation" base class class ExampleImpl : public ExampleIfce, public Implementation { // One-liner macro to register and bind this "ExampleImpl" implementation with the name "ExampleImplementation" to the "ExampleIfce" interface. RAMULATOR_REGISTER_IMPLEMENTATION(ExampleIfce, ExampleImpl, "ExampleImplementation", "An example of an implementation class.") public: // Implements concrete behavior virtual void foo() override { std::cout << "Bar!" << std::endl; }; }; } // namespace Ramulator ``` -------------------------------- ### Setup RowHammer Study Traces Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Downloads and extracts CPU traces required for the RowHammer mitigation study. ```bash cd rh_study wget # We host the traces here https://drive.google.com/file/d/1CvAenRZQmmM6s55ptG0-XyeLjhMVovTx/view?usp=drive_link tar xvzf ./cputraces.tar.gz ``` -------------------------------- ### Define an Example Interface Class in C++ Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Defines a basic interface class 'ExampleIfce' using Ramulator's registration macro. Include 'base/base.h' for fundamental data structures. This interface declares a virtual function 'foo()'. ```cpp // example_interface.h #ifndef RAMULATOR_EXAMPLE_INTERFACE_H #define RAMULATOR_EXAMPLE_INTERFACE_H // Defines fundamental data structures and types of Ramulator 2.0. Must include for all interfaces. #include "base/base.h" namespace Ramulator { class ExampleIfce { // One-liner macro to register this "ExampleIfce" interface with the name "ExampleInterface" to Ramulator 2.0. RAMULATOR_REGISTER_INTERFACE(ExampleIfce, "ExampleInterface", "An example of an interface class.") public: // Model common behaviors of the interface with virtual functions virtual void foo() = 0; }; } // namespace Ramulator #endif // RAMULATOR_EXAMPLE_INTERFACE_H ``` -------------------------------- ### Specify Ramulator Example Sources Source: https://github.com/cmu-safari/ramulator2/blob/main/src/example/CMakeLists.txt Lists the source files to be compiled for the 'ramulator-example' target. These files are marked as private, meaning they are not exposed to targets that link against this one. ```cmake target_sources( ramulator-example PRIVATE example_ifce.h impl/example_impl.cpp impl/example_serialization.cpp impl/complicated_impl.h impl/complicated_impl.cpp impl/another_impl.cpp impl/yetanother_impl.cpp ) ``` -------------------------------- ### Add Component Directory to CMakeLists.txt Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Example of how to add a new component directory to the main CMakeLists.txt file. This ensures that CMake includes the new component's source files in the build. ```cmake add_subdirectory(my_comp) ``` -------------------------------- ### Register Implementation Class in C++ Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Example of the macro used to register an implementation class with Ramulator. It links the implementation to its interface, specifies the implementation class name, and a description. ```cpp class MyImpl : public MyIfce, public Implementation { RAMULATOR_REGISTER_IMPLEMENTATION(MyIfce, MyImpl, "MyImplName", "An example of my implementation class.") } ``` -------------------------------- ### Link Ramulator Example Target Source: https://github.com/cmu-safari/ramulator2/blob/main/src/example/CMakeLists.txt Links the 'ramulator' library and the 'ramulator-example' target to the current target. The 'PRIVATE' keyword indicates that these dependencies are only needed for building the current target and are not propagated to other targets that link against it. ```cmake target_link_libraries( ramulator PRIVATE ramulator-example ) ``` -------------------------------- ### Add Ramulator Example Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/example/CMakeLists.txt Defines a new CMake library target named 'ramulator-example' of type OBJECT. This is typically used for static libraries or intermediate build targets. ```cmake add_library(ramulator-example OBJECT) ``` -------------------------------- ### Register Interface Class in C++ Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Example of the macro used to register an interface class with Ramulator. It specifies the class name, a unique string name, and a description. ```cpp class MyIfce { RAMULATOR_REGISTER_INTERFACE(MyIfce, "MyInterfaceName", "An example of my interface class.") } ``` -------------------------------- ### Get DRAM Clock Period in C++ Source: https://context7.com/cmu-safari/ramulator2/llms.txt Retrieve the DRAM clock period (tCK) from the initialized memory system object. This value is useful for timing-related calculations. ```cpp // Get the DRAM clock period float memory_tCK = ramulator2_memorysystem->get_tCK(); ``` -------------------------------- ### Create and Use Requests in C++ Source: https://context7.com/cmu-safari/ramulator2/llms.txt Demonstrates how to create read and write requests, including requests with callbacks for handling completion. Fields like address, type, source ID, and timing are accessible. ```cpp // Creating requests Request read_req(address, Request::Type::Read); Request write_req(address, Request::Type::Write); // Request with callback Request req(address, Request::Type::Read, source_id, [](Request& completed_req) { // Handle completion Addr_t addr = completed_req.addr; Clk_t latency = completed_req.depart - completed_req.arrive; }); // Request fields // req.addr - Physical address // req.addr_vec - DRAM address vector [channel, rank, bankgroup, bank, row, column] // req.type_id - 0=Read, 1=Write // req.source_id - Originating core/context // req.arrive - Arrival cycle at memory controller // req.depart - Departure cycle from memory controller ``` -------------------------------- ### Build and Run Simulators Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Builds the simulators, generates traces, and executes the performance comparison script. ```bash cd .. ./build_simulators.sh ``` ```bash cd traces ./gen_all_traces.sh ``` ```bash python3 perf_comparison.py ``` -------------------------------- ### Run Ramulator 2.0 Standalone Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Execute the simulator using a configuration file. ```bash $ ./ramulator2 -f ./example_config.yaml ``` -------------------------------- ### Clone and Build Ramulator 2.0 Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Commands to download the repository and compile the executable and dynamic library. ```bash $ git clone https://github.com/CMU-SAFARI/ramulator2 ``` ```bash $ mkdir build $ cd build $ cmake .. $ make -j $ cp ./ramulator2 ../ramulator2 $ cd .. ``` -------------------------------- ### Clone, Configure, and Build Ramulator 2.0 Source: https://context7.com/cmu-safari/ramulator2/llms.txt Clone the repository, then configure and build the simulator using CMake and make. This process generates the standalone executable and dynamic library. ```bash # Clone the repository git clone https://github.com/CMU-SAFARI/ramulator2 # Configure and build mkdir build cd build cmake .. make -j # Copy executables to project root cp ./ramulator2 ../ramulator2 cd .. ``` -------------------------------- ### Instantiate Ramulator 2.0 Components Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Parse YAML configuration and connect the frontend and memory system components. ```c++ // MyWrapper.h std::string config_path; Ramulator::IFrontEnd* ramulator2_frontend; Ramulator::IMemorySystem* ramulator2_memorysystem; // MyWrapper.cpp YAML::Node config = Ramulator::Config::parse_config_file(config_path, {}); ramulator2_frontend = Ramulator::Factory::create_frontend(config); ramulator2_memorysystem = Ramulator::Factory::create_memory_system(config); ramulator2_frontend->connect_memory_system(ramulator2_memorysystem); ramulator2_memorysystem->connect_frontend(ramulator2_frontend); ``` -------------------------------- ### Run Standalone Simulation with Configuration Source: https://context7.com/cmu-safari/ramulator2/llms.txt Execute the Ramulator 2.0 simulator using a YAML configuration file. Specific parameters can be overridden via the command line. ```bash # Run with a YAML configuration file ./ramulator2 -f ./example_config.yaml # Override specific parameters via command line ./ramulator2 -f ./example_config.yaml -p "MemorySystem.DRAM.timing.nRCD=20" ``` -------------------------------- ### Initialize Ramulator 2.0 Components in C++ Source: https://context7.com/cmu-safari/ramulator2/llms.txt Parse a YAML configuration file and create Ramulator 2.0 frontend and memory system components using the Factory pattern. Connect the frontend and memory system to enable communication. ```cpp // MyWrapper.h #include "ramulator2/src/base/base.h" #include "ramulator2/src/base/request.h" #include "ramulator2/src/base/config.h" #include "ramulator2/src/frontend/frontend.h" #include "ramulator2/src/memory_system/memory_system.h" std::string config_path; Ramulator::IFrontEnd* ramulator2_frontend; Ramulator::IMemorySystem* ramulator2_memorysystem; // MyWrapper.cpp - Initialization YAML::Node config = Ramulator::Config::parse_config_file(config_path, {}); ramulator2_frontend = Ramulator::Factory::create_frontend(config); ramulator2_memorysystem = Ramulator::Factory::create_memory_system(config); ramulator2_frontend->connect_memory_system(ramulator2_memorysystem); ramulator2_memorysystem->connect_frontend(ramulator2_frontend); ``` -------------------------------- ### Interact with Memory System in C++ Source: https://context7.com/cmu-safari/ramulator2/llms.txt Shows how to send requests to the memory system, advance the simulation by one clock cycle, and retrieve the clock ratio relative to the processor. ```cpp // Send request to memory system bool success = memory_system->send(request); // Tick the memory system (call every memory clock cycle) memory_system->tick(); // Get clock ratio relative to processor int ratio = memory_system->get_clock_ratio(); ``` -------------------------------- ### Ramulator 2.0 Directory Structure Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Overview of the project directory layout. ```text ext # External libraries src # Source code of Ramulator 2.0 └ # Collection of the source code of all interfaces and implementations related to the component └ impl # Collection of the source code of all implementations of the component └ com_impl.cpp # Source file of a specific implementation └ com_interface.h # Header file that defines an interface └ CMakeList.txt # Component-level CMake configuration └ ... └ CMakeList.txt # Top-level CMake configuration of all Ramulator 2.0's source files CMakeList.txt # Project-level CMake configuration ``` -------------------------------- ### Automate Experiments with Python Parameter Sweeps Source: https://context7.com/cmu-safari/ramulator2/llms.txt Automate Ramulator2 simulations by sweeping parameters using Python. Load a baseline config, modify parameters, and run subprocesses for each configuration. ```python import os import yaml import subprocess baseline_config_file = "./example_config.yaml" nRCD_list = [10, 15, 20, 25] nRP_list = [10, 12, 14] # Load base configuration with open(baseline_config_file, 'r') as f: base_config = yaml.safe_load(f) results = [] for nRCD in nRCD_list: for nRP in nRP_list: # Modify configuration config = base_config.copy() config["MemorySystem"]["DRAM"]["timing"]["nRCD"] = nRCD config["MemorySystem"]["DRAM"]["timing"]["nRP"] = nRP # Run simulation with dumped YAML result = subprocess.run( ["./ramulator2", "-c", str(config)], capture_output=True, text=True ) results.append({ "nRCD": nRCD, "nRP": nRP, "output": result.stdout }) # Process results... ``` -------------------------------- ### Integrate Ramulator 2.0 into gem5 Build System Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md SConscript configuration to link the Ramulator 2.0 dynamic library into the gem5 build process. ```python import os Import('env') if not os.path.exists(Dir('.').srcnode().abspath + '/ramulator2'): env['HAVE_RAMULATOR2'] = False Return() env['HAVE_RAMULATOR2'] = True ramulator2_path = os.path.join(Dir('#').abspath, 'ext/ramulator2/ramulator2/') env.Prepend(CPPPATH=Dir('.').srcnode()) env.Append( LIBS=['ramulator'], LIBPATH=[ramulator2_path], RPATH=[ramulator2_path], CPPPATH=[ ramulator2_path+'/src/', ramulator2_path+'/ext/spdlog/include', ramulator2_path+'/ext/yaml-cpp/include' ]) ``` -------------------------------- ### Generate and Verify DRAM Commands with Bash Source: https://context7.com/cmu-safari/ramulator2/llms.txt A sequence of bash commands to generate instruction traces, run Ramulator simulation, convert the trace for Verilog testbench, and verify the output with a Verilog simulator. ```bash # Generate instruction traces cd verilog_verification/traces python3 tracegen.py --type SimpleO3 --pattern stream --num-insts 10000 --output test.trace --distance 100 # Run simulation to collect DRAM command trace cd .. ./ramulator2 -f ./verification-config.yaml # Convert trace for Verilog testbench python3 trace_converter.py DDR4_8G_X8 2 DDR4_2400 # Verify with Verilog simulator output python3 trace_verifier.py ``` -------------------------------- ### Configure Custom Interface Implementation via YAML Source: https://context7.com/cmu-safari/ramulator2/llms.txt Specify the custom interface implementation and its parameters in the YAML configuration file. ```yaml MyInterfaceName: impl: MyImplName value_param: 42 threshold: 0.5 optional_flag: true ``` -------------------------------- ### Implement a Custom Interface Source: https://context7.com/cmu-safari/ramulator2/llms.txt Implement the interface's pure virtual functions and register the implementation using RAMULATOR_REGISTER_IMPLEMENTATION. Use param<> to parse configuration. ```cpp // my_impl.cpp #include "my_interface.h" namespace Ramulator { class MyImpl : public MyIfce, public Implementation { RAMULATOR_REGISTER_IMPLEMENTATION(MyIfce, MyImpl, "MyImplName", "Description of my implementation.") private: int m_value; public: void init() override { // Parse configuration parameters m_value = param("value_param").desc("A value parameter").default_val(10); // Required parameter (throws if missing) float threshold = param("threshold").required(); // Optional parameter auto opt_flag = param("optional_flag").optional(); if (opt_flag) { // Use optional value } } void foo() override { // Implementation } int get_value() override { return m_value; } }; } // namespace Ramulator ``` -------------------------------- ### FetchContent Configuration for External Libraries Source: https://github.com/cmu-safari/ramulator2/blob/main/CMakeLists.txt Configures FetchContent to skip updates after the first population and sets up the declaration for fetching external libraries like yaml-cpp, spdlog, and argparse from their respective Git repositories. ```cmake #### External libraries #### include(FetchContent) set(FETCHCONTENT_UPDATES_DISCONNECTED ON CACHE BOOL "Skip updating the external dependencies after populating them for the first time") message("Configuring yaml-cpp...") option(YAML_CPP_BUILD_CONTRIB "Enable yaml-cpp contrib in library" OFF) option(YAML_CPP_BUILD_TOOLS "Enable parse tools" OFF) option(YAML_BUILD_SHARED_LIBS "Build yaml-cpp as a shared library" OFF) FetchContent_Declare( yaml-cpp GIT_REPOSITORY https://github.com/jbeder/yaml-cpp.git GIT_TAG yaml-cpp-0.7.0 SOURCE_DIR ${CMAKE_SOURCE_DIR}/ext/yaml-cpp ) FetchContent_MakeAvailable(yaml-cpp) include_directories(${yaml-cpp_SOURCE_DIR}/include) message("Done configuring yaml-cpp.") message("Configuring spdlog...") FetchContent_Declare( spdlog GIT_REPOSITORY https://github.com/gabime/spdlog.git GIT_TAG v1.11.0 SOURCE_DIR ${CMAKE_SOURCE_DIR}/ext/spdlog ) FetchContent_MakeAvailable(spdlog) include_directories(${spdlog_SOURCE_DIR}/include) message("Done configuring spdlog.") message("Configuring argparse...") FetchContent_Declare( argparse GIT_REPOSITORY https://github.com/p-ranav/argparse.git GIT_TAG v2.9 SOURCE_DIR ${CMAKE_SOURCE_DIR}/ext/argparse ) FetchContent_MakeAvailable(argparse) include_directories(${argparse_SOURCE_DIR}/include) message("Done configuring argparse.") ################################## ``` -------------------------------- ### Register Ramulator 2.0 SimObjects in gem5 Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Registration of SimObjects within the gem5 SConscript file. ```python if env['HAVE_RAMULATOR2']: SimObject('Ramulator2.py', sim_objects=['Ramulator2']) Source('ramulator2.cc') DebugFlag("Ramulator2") ``` -------------------------------- ### Verify Simulation Output Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Parses the simulation output to check for timing or state transition violations. ```bash python3 trace_verifier.py ``` -------------------------------- ### YAML Configuration for Interface Implementation Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Specifies the implementation for an interface in the YAML configuration file. This allows Ramulator to automatically construct the correct object type based on the configuration. ```yaml MyInterfaceName: impl: MyImplName ``` -------------------------------- ### Run RowHammer Simulations Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Generates workload combinations and executes single-core and multi-core simulations. ```bash python3 get_trace_combinations.py ``` ```bash python3 run_singlecore.py python3 run_multicore.py ``` -------------------------------- ### Generate Instruction Traces for Verification Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Generates instruction traces for the DRAM verification process using the tracegen script. ```bash cd verilog_verification cd traces python3 tracegen.py --type SimpleO3 --pattern {stream,random} --num-insts ${NUM_INSTS} --output ${TRACE_FILE} --distance ${MEMREQ_INTENSITY} ``` -------------------------------- ### Apply Simulator Patches Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Applies patches to external simulators to unify configuration and termination criteria. ```bash cd DRAMSim2 git apply ../../DRAMSim2-patch.patch cd .. cd DRAMsim3 git apply ../../DRAMsim3-patch.patch cd .. ``` -------------------------------- ### Collect DRAM Command Trace Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Executes the Ramulator 2.0 simulation to collect command traces based on the provided configuration. ```bash cd .. ./ramulator2 -f ./verification-config.yaml ``` -------------------------------- ### Add Subdirectories in CMakeLists.txt Source: https://github.com/cmu-safari/ramulator2/blob/main/src/CMakeLists.txt These commands are used in CMakeLists.txt to include subdirectories, organizing the project into modular components. ```cmake add_subdirectory(base) ``` ```cmake add_subdirectory(test) ``` ```cmake add_subdirectory(frontend) ``` ```cmake add_subdirectory(translation) ``` ```cmake add_subdirectory(memory_system) ``` ```cmake add_subdirectory(addr_mapper) ``` ```cmake add_subdirectory(dram) ``` ```cmake add_subdirectory(dram_controller) ``` -------------------------------- ### Define Ramulator2 Base Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/base/CMakeLists.txt Creates an object library named ramulator-base and specifies its source files. ```cmake add_library(ramulator-base OBJECT) target_sources( ramulator-base PRIVATE base.h factory.h factory.cpp type.h exception.h logging.h logging.cpp debug.h param.h utils.h utils.cpp config.h config.cpp clocked.h stats.h stats.cpp request.h request.cpp serialization.h ) ``` -------------------------------- ### Ramulator2 Library and Executable Build Source: https://github.com/cmu-safari/ramulator2/blob/main/CMakeLists.txt Defines the 'ramulator' shared library and the 'ramulator-exe' executable. It links the necessary libraries and sets the output name for the executable. ```cmake include_directories(${CMAKE_SOURCE_DIR}/src) add_library(ramulator SHARED) set_target_properties(ramulator PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR} ) target_link_libraries( ramulator PUBLIC yaml-cpp PUBLIC spdlog ) add_executable(ramulator-exe) target_link_libraries( ramulator-exe # PRIVATE -Wl,--whole-archive ramulator -Wl,--no-whole-archive PRIVATE ramulator PRIVATE argparse ) set_target_properties( ramulator-exe PROPERTIES OUTPUT_NAME ramulator2 ) add_subdirectory(src) ``` -------------------------------- ### Configure Ramulator2 Test Library with CMake Source: https://github.com/cmu-safari/ramulator2/blob/main/src/test/CMakeLists.txt Defines an object library for testing and links it to the main ramulator target. ```cmake add_library(ramulator-test OBJECT) target_sources( ramulator-test PRIVATE test_ifce.h test_impl.cpp ) target_link_libraries( ramulator PRIVATE ramulator-test ) ``` -------------------------------- ### Load and Process Multicore Trace Data Source: https://github.com/cmu-safari/ramulator2/blob/main/rh_study/plot.ipynb Reads trace combination data, calculates IPC for single-core runs, and then processes multicore results for different mitigation techniques to compute weighted speedup. Requires pre-defined output paths and trace combination filenames. ```python multicore_out_path = "./results_multicore" singlecore_out_path = "./results_singlecore" trace_combination_filename = "multicore_traces.txt" trace_combs = {} with open(trace_combination_filename, "r") as trace_combination_file: for line in trace_combination_file: line = line.strip() if(line == ""): continue trace_name = line.split(",")[0] trace_list = line.split(",")[1:] trace_combs[trace_name] = trace_list ipc_alone = {} result_path = singlecore_out_path + "/NoDefence/stats/" result_list = [x[:-4] for x in os.listdir(result_path) if (x.endswith(".txt") and x.startswith("100"))] for result_filename in result_list: result_file = open(result_path + "/" + result_filename + ".txt", "r") trace = result_filename.split("_")[1] core_0 = 0 for line in result_file.readlines(): if (" cycles_recorded_core_0:" in line): core_0 = int(line.split(" ")[-1]) ipc_alone[trace] = 100000000 / core_0 result_file.close() df = pd.DataFrame(columns=["mitigation", "trh", "trace", "ws"]) mitigation_list = ["PARA", "Hydra", "TWiCe-Ideal", "Graphene", "OracleRH", "RSS", "NoDefence"] for mitigation in mitigation_list: result_path = multicore_out_path + "/" + mitigation + "/stats/" result_list = [x[:-4] for x in os.listdir(result_path) if x.endswith(".txt")] for result_filename in result_list: result_file = open(result_path + "/" + result_filename + ".txt", "r") trh = int(result_filename.split("_")[0]) trace = result_filename.split("_")[1] ipc_0 = 0 ipc_1 = 0 ipc_2 = 0 ipc_3 = 0 trace_0, trace_1, trace_2, trace_3 = trace_combs[trace] for line in result_file.readlines(): if (" cycles_recorded_core_0:" in line): ipc_0 = 100000000 / int(line.split(" ")[-1]) if (" cycles_recorded_core_1:" in line): ipc_1 = 100000000 / int(line.split(" ")[-1]) if (" cycles_recorded_core_2:" in line): ipc_2 = 100000000 / int(line.split(" ")[-1]) if (" cycles_recorded_core_3:" in line): ipc_3 = 100000000 / int(line.split(" ")[-1]) if (ipc_0 == 0 and ipc_1 == 0 and ipc_2 == 0 and ipc_3 == 0): continue if (ipc_0 == 0 or ipc_1 == 0 or ipc_2 == 0 or ipc_3 == 0): print("Error: " + result_filename) weighted_speedup = ipc_0 / ipc_alone[trace_0] + ipc_1 / ipc_alone[trace_1] + ipc_2 / ipc_alone[trace_2] + ipc_3 / ipc_alone[trace_3] result_file.close() df = df.append({'mitigation': mitigation, 'trh': trh, 'trace': trace, 'ws': weighted_speedup}, ignore_index=True) df = df.pivot(index=['trh', 'trace'], columns=['mitigation'], values='ws').reset_index() for mitigation in set(mitigation_list) - set(['NoDefence']): df[mitigation] = df[mitigation] / df['NoDefence'] df['NoDefence'] = 1 df.drop(['NoDefence'], 1, inplace=True) df.rename(columns={'OracleRH': 'Ideal'}, inplace=True) df = df.melt(id_vars=['trh', 'trace'], var_name='mitigation', value_name='norm_ws') ``` -------------------------------- ### Ramulator2 CMake Configuration Source: https://github.com/cmu-safari/ramulator2/blob/main/CMakeLists.txt Sets up the minimum CMake version, project name, version, and language. It also forces the build type to 'Release' if not already set and enables independent code compilation. ```cmake cmake_minimum_required(VERSION 3.14) project( Ramulator VERSION 2.0 LANGUAGES CXX ) #### Prompt the build type #### if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE) endif() message("Configuring ${CMAKE_PROJECT_NAME} ${CMAKE_PROJECT_Version}...") message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DRAMULATOR_DEBUG") # set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}") set(CMAKE_POSITION_INDEPENDENT_CODE ON) ############################### ``` -------------------------------- ### Import Libraries for Performance Analysis Source: https://github.com/cmu-safari/ramulator2/blob/main/rh_study/plot.ipynb Imports necessary Python libraries for data manipulation, plotting, and file system operations. Includes warnings suppression. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os import warnings warnings.filterwarnings('ignore') ``` -------------------------------- ### Ramulator2 C++ Standard and Compile Commands Source: https://github.com/cmu-safari/ramulator2/blob/main/CMakeLists.txt Enables the export of compile commands for debugging and sets the C++ standard to C++20, requiring it and disabling extensions. ```cmake set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE INTERNAL "") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### Define and link ramulator-addrmapper library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/addr_mapper/CMakeLists.txt Configures the address mapper object library and links it as a private dependency to the ramulator target. ```cmake add_library(ramulator-addrmapper OBJECT) target_sources( ramulator-addrmapper PRIVATE addr_mapper.h impl/linear_mappers.cpp impl/rit.cpp impl/rit.h ) target_link_libraries( ramulator PRIVATE ramulator-addrmapper ) ``` -------------------------------- ### Implement RowHammer Mitigation Plugin Source: https://context7.com/cmu-safari/ramulator2/llms.txt Implement IControllerPlugin to create custom RowHammer mitigation logic. Use param<> for configuration and access DRAM details via m_dram. ```cpp #include "base/base.h" #include "dram_controller/controller.h" #include "dram_controller/plugin.h" namespace Ramulator { class MyMitigation : public IControllerPlugin, public Implementation { RAMULATOR_REGISTER_IMPLEMENTATION(IControllerPlugin, MyMitigation, "MyMitigation", "Custom RowHammer mitigation.") private: IDRAM* m_dram = nullptr; int m_activation_threshold = -1; int m_row_level = -1; public: void init() override { m_activation_threshold = param("activation_threshold").required(); } void setup(IFrontEnd* frontend, IMemorySystem* memory_system) override { m_ctrl = cast_parent(); m_dram = m_ctrl->m_dram; m_row_level = m_dram->m_levels("row"); } void update(bool request_found, ReqBuffer::iterator& req_it) override { if (request_found) { // Check if command is a row activation if (m_dram->m_command_meta(req_it->command).is_opening && m_dram->m_command_scopes(req_it->command) == m_row_level) { int row_id = req_it->addr_vec[m_row_level]; // Implement mitigation logic... // Schedule preventive refresh if needed // Request vrr_req(req_it->addr_vec, m_VRR_req_id); // m_ctrl->priority_send(vrr_req); } } } }; } // namespace Ramulator ``` -------------------------------- ### Send Memory Requests with Callbacks in C++ Source: https://context7.com/cmu-safari/ramulator2/llms.txt Enqueue memory read or write requests to the Ramulator 2.0 frontend. A callback function is provided to handle the completion of each request, allowing access to request details like address and timing. ```cpp // Send a read request (type_id = 0) bool enqueue_success = ramulator2_frontend-> receive_external_requests(0, memory_address, context_id, [this](Ramulator::Request& req) { // Callback executed when read completes // Access req.addr, req.depart for timing info }); if (enqueue_success) { // Request accepted by memory system } else { // Request rejected (e.g., queue full), retry later } // Send a write request (type_id = 1) enqueue_success = ramulator2_frontend-> receive_external_requests(1, memory_address, context_id, [this](Ramulator::Request& req) { // Callback executed when write completes }); ``` -------------------------------- ### Convert DRAM Command Trace Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Converts the collected DRAM command trace into a format compatible with the Verilog model testbench. ```bash python3 trace_converter.py DDR4_8G_X8 2 DDR4_2400 ``` -------------------------------- ### Send Memory Requests Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Enqueue external memory requests to the frontend with a completion callback. ```c++ if (is_read_request) { enqueue_success = ramulator2_frontend-> receive_external_requests(0, memory_address, context_id, [this](Ramulator::Request& req) { // your read request callback }); if (enqueue_success) { // What happens if the memory request is accepted by Ramulator 2.0 } else { // What happens if the memory request is rejected by Ramulator 2.0 (e.g., request queue full) } } ``` -------------------------------- ### Configure Ramulator2 DRAM Library in CMake Source: https://github.com/cmu-safari/ramulator2/blob/main/src/dram/CMakeLists.txt Defines the ramulator-dram object library and links it to the main project target. ```cmake add_library(ramulator-dram OBJECT) target_sources( ramulator-dram PRIVATE dram.h node.h spec.h lambdas.h lambdas/preq.h lambdas/rowhit.h lambdas/rowopen.h lambdas/action.h lambdas/power.h impl/DDR3.cpp impl/DDR4.cpp impl/DDR4-VRR.cpp impl/DDR4-RVRR.cpp impl/DDR5.cpp impl/DDR5-VRR.cpp impl/DDR5-RVRR.cpp impl/LPDDR5.cpp impl/HBM.cpp impl/HBM2.cpp impl/HBM3.cpp ) target_link_libraries( ramulator PRIVATE ramulator-dram ) ``` -------------------------------- ### Link Ramulator Memory System to Ramulator Source: https://github.com/cmu-safari/ramulator2/blob/main/src/memory_system/CMakeLists.txt Links the 'ramulator-memorysystem' library to the main 'ramulator' target. This makes the compiled object files from the memory system available to the 'ramulator' executable or library. ```cmake target_link_libraries( ramulator PRIVATE ramulator-memorysystem ) ``` -------------------------------- ### Define a Custom Interface Class Source: https://context7.com/cmu-safari/ramulator2/llms.txt Define common behaviors with pure virtual functions in an interface class. Ensure it's registered with RAMULATOR_REGISTER_INTERFACE. ```cpp // my_interface.h #ifndef RAMULATOR_MY_INTERFACE_H #define RAMULATOR_MY_INTERFACE_H #include "base/base.h" namespace Ramulator { class MyIfce { RAMULATOR_REGISTER_INTERFACE(MyIfce, "MyInterfaceName", "Description of my interface.") public: // Define common behaviors with pure virtual functions virtual void foo() = 0; virtual int get_value() = 0; }; } // namespace Ramulator #endif // RAMULATOR_MY_INTERFACE_H ``` -------------------------------- ### Add Sources to Ramulator Translation Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/translation/CMakeLists.txt Specifies the source files for the 'ramulator-translation' library. These sources are compiled as part of this OBJECT library. ```cmake target_sources( ramulator-translation PRIVATE translation.h impl/no_translation.cpp impl/random_translation.cpp ) ``` -------------------------------- ### Tick Memory System and Finalize Simulation Source: https://context7.com/cmu-safari/ramulator2/llms.txt Call tick() in the main simulation loop and finalize() when the simulation ends. ```cpp // Call in simulation main loop ramulator2_memorysystem->tick(); // Call when simulation ends void my_simulator_finish() { ramulator2_frontend->finalize(); ramulator2_memorysystem->finalize(); } ``` -------------------------------- ### Link Ramulator Frontend to Ramulator Target Source: https://github.com/cmu-safari/ramulator2/blob/main/src/frontend/CMakeLists.txt Links the ramulator-frontend object library to the main ramulator target. This ensures that the compiled code from ramulator-frontend is included when building the ramulator executable or library. ```cmake target_link_libraries( ramulator PRIVATE ramulator-frontend ) ``` -------------------------------- ### Define Ramulator2 Executable Target Source: https://github.com/cmu-safari/ramulator2/blob/main/src/CMakeLists.txt This CMake command defines the main executable target 'ramulator-exe' and specifies its source files. ```cmake target_sources( ramulator-exe PRIVATE main.cpp ) ``` -------------------------------- ### Register Controller Plugin in Configuration Source: https://context7.com/cmu-safari/ramulator2/llms.txt Register the custom controller plugin in the YAML configuration under the 'plugins' section. ```yaml Controller: impl: Generic plugins: - ControllerPlugin: impl: MyMitigation activation_threshold: 1000 ``` -------------------------------- ### Define Ramulator Frontend Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/frontend/CMakeLists.txt Defines the ramulator-frontend library as an object library in CMake. This is typically used for organizing source files that will be linked into other targets. ```cmake add_library(ramulator-frontend OBJECT) target_sources( ramulator-frontend PRIVATE frontend.h impl/memory_trace/loadstore_trace.cpp impl/memory_trace/readwrite_trace.cpp impl/processor/simpleO3/simpleO3.cpp impl/processor/simpleO3/core.h impl/processor/simpleO3/core.cpp impl/processor/simpleO3/llc.h impl/processor/simpleO3/llc.cpp impl/processor/simpleO3/trace.h impl/processor/simpleO3/trace.cpp impl/processor/bhO3/bhO3.h impl/processor/bhO3/bhO3.cpp impl/processor/bhO3/bhcore.h impl/processor/bhO3/bhcore.cpp impl/processor/bhO3/bhllc.h impl/processor/bhO3/bhllc.cpp impl/external_wrapper/gem5_frontend.cpp ) ``` -------------------------------- ### Link Ramulator Translation Library to Ramulator Source: https://github.com/cmu-safari/ramulator2/blob/main/src/translation/CMakeLists.txt Links the 'ramulator-translation' library to the main 'ramulator' target. This makes the compiled object files from 'ramulator-translation' available to the 'ramulator' executable or library. ```cmake target_link_libraries( ramulator PRIVATE ramulator-translation ) ``` -------------------------------- ### Configuration with RowHammer Mitigation (BlockHammer) Source: https://context7.com/cmu-safari/ramulator2/llms.txt A YAML configuration for a DDR5 memory system incorporating RowHammer mitigation using the BlockHammer plugin. This configuration includes specific settings for DRAM, controller, and plugins. ```yaml Frontend: impl: BHO3 clock_ratio: 8 num_expected_insts: 500000 llc_capacity_per_core: 2MB llc_num_mshr_per_core: 16 inst_window_depth: 128 traces: - example_inst.trace no_wait_traces: - example_rh_physaddr.trace Translation: impl: RandomTranslation max_addr: 17179869184 MemorySystem: impl: BHDRAMSystem clock_ratio: 3 DRAM: impl: DDR5-VRR org: preset: DDR5_16Gb_x8 channel: 1 rank: 2 timing: preset: DDR5_3200AN RFM: BRC: 2 BHDRAMController: impl: BHDRAMController BHScheduler: impl: BLISS RefreshManager: impl: AllBank RowPolicy: impl: ClosedRowPolicy cap: 4 plugins: - ControllerPlugin: blacklist_thresh: 4 unblacklist_cycles: 10000 impl: BLISS - ControllerPlugin: rfm_thresh: 80 impl: RFMManager - ControllerPlugin: bf_ctr_thresh: 1024 bf_num_rh: 4096 impl: BlockHammer AddrMapper: impl: RoBaRaCoCh_with_rit ``` -------------------------------- ### Link Ramulator2 Base Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/base/CMakeLists.txt Links the ramulator-base object library to the ramulator target. ```cmake target_link_libraries( ramulator PRIVATE ramulator-base ) ``` -------------------------------- ### Finalize Ramulator 2.0 Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Call finalize functions on components upon simulator completion. ```c++ void my_simulator_finish() { ramulator2_frontend->finalize(); ramulator2_memorysystem->finalize(); } ``` -------------------------------- ### Add Sources to Ramulator Memory System Source: https://github.com/cmu-safari/ramulator2/blob/main/src/memory_system/CMakeLists.txt Specifies the source files to be included in the 'ramulator-memorysystem' target. These sources are compiled privately for this target. ```cmake target_sources( ramulator-memorysystem PRIVATE bh_memory_system.h memory_system.h impl/bh_DRAM_system.cpp impl/dummy_memory_system.cpp impl/generic_DRAM_system.cpp ) ``` -------------------------------- ### Retrieve Memory System Clock Source: https://github.com/cmu-safari/ramulator2/blob/main/README.md Access the memory system clock period from the memory system instance. ```c++ float memory_tCK = ramulator2_memorysystem->get_tCK(); ``` -------------------------------- ### Visualize Performance Data with Seaborn Source: https://github.com/cmu-safari/ramulator2/blob/main/rh_study/plot.ipynb Generates a line plot showing normalized weighted speedup across different RowHammer thresholds and mitigation techniques. Customizes plot aesthetics, including axes, ticks, labels, and legend. ```python fig, ax = plt.subplots(figsize=(11, 4.5)) # plot the data as a line plot with markers and errorbars with larger markers and put ticks at both ends of the errorbars sns.lineplot(x='trh', y='norm_ws', hue='mitigation', data=df, ax=ax, linewidth=2.5, markers=True, dashes=False, style='mitigation', markersize=12, errorbar=("sd"), err_style='bars', hue_order=['PARA', 'Hydra', 'TWiCe-Ideal', 'Graphene', 'RSS', 'Ideal'], err_kws={'capsize': 4, 'elinewidth': 2, 'capthick': 2} ) plt.grid(axis='both', linestyle='--') #make x axis reversed plt.gca().invert_xaxis() plt.xscale('log') x_ticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000] ax.set_xticks(x_ticks) ax.set_xticklabels(x_ticks, fontsize=14) y_ticks = [0, 0.2, 0.4, 0.6, 0.8, 1.0] ax.axhline(y=1.0, color='red', linestyle='--', zorder=0) ax.set_yticks(y_ticks) ax.set_yticklabels(y_ticks, fontsize=14) ax.set_xlabel("RowHammer Threshold (tRH)", fontsize=18, weight="bold") ax.set_ylabel("Normalized WS", fontsize=18, weight="bold") for axis in ['top','bottom','left','right']: ax.spines[axis].set_linewidth(1.3) # plt.legend(bbox_to_anchor=(0.5, 1.12), loc='upper center', ncol=6, # fontsize=12, # edgecolor='black' # ) plt.legend(loc='lower left', ncol=1, fontsize=15, edgecolor='black' ) ``` -------------------------------- ### Define Ramulator Memory System Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/memory_system/CMakeLists.txt Defines a CMake library target named 'ramulator-memorysystem' as an OBJECT library. This is typically used for compiling source files that will be linked into other targets. ```cmake add_library(ramulator-memorysystem OBJECT) ``` -------------------------------- ### Define Ramulator Translation Library Source: https://github.com/cmu-safari/ramulator2/blob/main/src/translation/CMakeLists.txt Defines a CMake library target named 'ramulator-translation' as an OBJECT library. This is typically used for compiling source files that will be linked into other targets. ```cmake add_library(ramulator-translation OBJECT) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.