cma_approach_square_size.py 16.1 KB
Newer Older
harry1080ti's avatar
harry1080ti committed
1 2 3 4 5
import cma
from multiprocessing import Pool
from os import cpu_count
import time
import path_constant as pc
harry1080ti's avatar
harry1080ti committed
6
import packing_penalty as pp
7
from os import makedirs
Justin Borromeo's avatar
Justin Borromeo committed
8
from copy import deepcopy
harry1080ti's avatar
harry1080ti committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

class cma_approach(object):
    def __init__(self,
        # data path
        path_to_datasrc = "alexnet_data.csv",
        path_to_topology = "alexnet.csv",
        target_col = "Cycles",

        # problem definition
        number_of_partition = 4, max_iteration = 100,
        sigma = 0.5, population_size = 10,

        # constraint
        max_res_unit = 960, initial_res = 0,
        res_step = 1,
        penalty_offest = 10000000000,
        seeding_type="optimised",
26
        hybrid = True,
harry1080ti's avatar
harry1080ti committed
27 28
        print_to_csv = True,
        max_pack_size = 129
harry1080ti's avatar
harry1080ti committed
29 30 31 32 33 34 35 36 37 38 39
        ):
        self.target_col = target_col
        self.start = time.time()
        self.k = number_of_partition
        self.max_iter = max_iteration
        self.sigma = sigma
        self.max_res_unit = max_res_unit
        self.res_step = res_step
        self.population_size = population_size
        self.penalty_offest = penalty_offest
        self.ending_iter = 0
40
        self.is_hybrid = hybrid
harry1080ti's avatar
harry1080ti committed
41 42 43 44 45 46 47 48 49 50 51 52 53
        self.data_src = {}

        self.topology_file = path_to_topology
        self.layers = self.parse_topology_file()
        self.parse_data_set_file(path_to_datasrc)

        self.best_layer = number_of_partition * [0]
        self.best_res = number_of_partition * [0]

        self.total_valid_solution = 0
        self.trial = 1
        self.seeding_type = seeding_type

54
        self.max_res_available = max_res_unit
harry1080ti's avatar
harry1080ti committed
55
        self.print_to_csv = print_to_csv
harry1080ti's avatar
harry1080ti committed
56

harry1080ti's avatar
harry1080ti committed
57 58
        self.max_pack_size = max_pack_size

harry1080ti's avatar
harry1080ti committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    def parse_topology_file(self):
        layers = []
        with open(pc.TOPOLOGIES_PATH+self.topology_file, 'r') as f:
            next(f)
            for line in f:
                elems = line.strip().split(',')
                layers.append(elems[0])

        for layer in layers:
            self.data_src[layer] = {}
        return layers

    def parse_data_set_file(self, path_to_data_csv):
        first = True
        target_idx = 2
        with open(pc.DATA_SOURCE_PATH+path_to_data_csv, 'r') as f:
            for line in f:
                elems = line.strip().split(',')
                # print(elems)
                if first:
                    for idx, col in enumerate(elems):
                        if self.target_col in col:
                            target_idx = idx
                            break
                    first = False
                else:
                    self.data_src[elems[1]][int(elems[0])] = int(float(elems[target_idx]))

    def regroup_layers(self, sample):
        # #print("DEBUG", sample)
        detail_sample = []
        idx = 0
        for size in sample:
            part = []

            if size == 1:
                part.append(self.layers[idx])
                idx += 1
            else:
                for i in range(0, size):
                    part.append(self.layers[i + idx])
                idx += size

            detail_sample.append(part)

        return detail_sample

    def decode(self, val, max_val):
        return int(val * max_val)

    def encode(self, val, max_val):
        return float(val / max_val)

    def filter_layer(self, layer):
        for idx in range(self.k):
            if layer[idx] <= 0:
                return False

        if sum(layer) != len(self.layers):
            return False

        return True

    def filter_res(self, res):
        # #print(layer, res)
        for idx in range(self.k):
            if res[idx] <= 0:
                return False

        if sum(res) != self.max_res_unit:
            return False

        return True

    def penalty_layer(self, layer):
        penalty_score = self.penalty_offest

        if sum(layer) != len(self.layers):
            penalty_score += self.penalty_offest
        else:
            layer = [abs(val) for val in layer]

        for idx in range(self.k):
            if layer[idx] <= 0:
                penalty_score *= 1.05

        percent_diff = (abs(sum(layer) - len(self.layers)) / len(self.layers))
        penalty_score += percent_diff * self.penalty_offest

        return penalty_score

    def find_max_latency(self, layer_partition, res_partitions):
        latencies = [0] * len(layer_partition)
        max_latency_idx = 0
        # print(layer_partition)
        # print(res_partitions)
        for idx, part in enumerate(layer_partition):
            res = res_partitions[idx]
            for layer in part:
                latencies[idx] += self.data_src[layer][res]
            if latencies[idx] > latencies[max_latency_idx]:
                max_latency_idx = idx

        return latencies, max_latency_idx

justinborromeo's avatar
WIP  
justinborromeo committed
164
    """
Justin Borromeo's avatar
Justin Borromeo committed
165 166
    Decide partition sizes and evaluate the soln.  Should always return a 
    packable solution.
justinborromeo's avatar
WIP  
justinborromeo committed
167
    """
168
    def eva_hybrid_sq(self, layer):
Justin Borromeo's avatar
.  
Justin Borromeo committed
169 170
        # res is a list where each element corresponds to a partition.  res_step
        # is the minimum amount by which partition edge length increases.
harry1080ti's avatar
harry1080ti committed
171 172
        res = [self.res_step] * self.k
        latencies = []
justinborromeo's avatar
WIP  
justinborromeo committed
173 174 175 176

        # max_res_unit = 1920*9*1 from sq_approach_faster
        variable_max_res_unit = self.max_res_unit
        
177 178 179
        # Do a binary search to find the largest packable variable_max_res_unit.
        search_upper_bound = self.max_res_unit
        search_lower_bound = sum([r*r for r in res])
Justin Borromeo's avatar
Justin Borromeo committed
180 181 182 183

        last_packable_res = []
        last_packable_max_res_unit = 0
        while search_upper_bound > search_lower_bound:
184 185 186 187
            variable_max_res_unit = \
                int((search_upper_bound + search_lower_bound)/2)
            limit_reached = False
            while not limit_reached:
justinborromeo's avatar
WIP  
justinborromeo committed
188 189
                latencies, max_idx = self.find_max_latency(layer, res)
                res[max_idx] += self.res_step
190 191 192 193 194 195 196
                # If this addition puts the solution over the limit, we need to
                # revert the last partition addition.  TODO write some code to
                # see if we can assign the remaining units.
                if sum([r**2 for r in res]) > variable_max_res_unit:
                    res[max_idx] -= self.res_step
                    limit_reached = True
            if pp.isPackable(res, self.max_pack_size):
Justin Borromeo's avatar
Justin Borromeo committed
197 198
                last_packable_res = deepcopy(res)
                last_packable_max_res_unit = variable_max_res_unit
199 200 201 202 203 204 205 206 207
                # The desired max_res_unit value is greater than its current
                # value.
                search_lower_bound = variable_max_res_unit
            else:
                # The desired max_res_unit value is less than its current 
                # value.
                search_upper_bound = variable_max_res_unit

        # Calculate latencies of final solution.
Justin Borromeo's avatar
Justin Borromeo committed
208
        latencies, max_idx = self.find_max_latency(layer, last_packable_res)
justinborromeo's avatar
WIP  
justinborromeo committed
209 210 211 212

        # TODO we want to penalize based on how much we had to decrease
        # variable_max_res_unit.
        max_res_unit_decrease = self.max_res_unit - variable_max_res_unit
213
        packing_penalty = pp.calculatePackingPenalty(max_res_unit_decrease)
Justin Borromeo's avatar
Justin Borromeo committed
214
        return latencies[max_idx] + packing_penalty, latencies, last_packable_res, layer
harry1080ti's avatar
harry1080ti committed
215 216 217 218 219 220 221 222 223

    def evaluation_top_level(self, in_val):
        pid, sampling = in_val
        layer = [self.decode(val, len(self.layers)) for val in sampling]
        layer.append(len(self.layers) - sum(layer))
        penalty = 0

        if not self.filter_layer(layer):
            penalty = self.penalty_layer(layer)
224
            if self.is_hybrid:
harry1080ti's avatar
harry1080ti committed
225 226 227 228
                return pid, penalty
            else:
                return pid, penalty*4

justinborromeo's avatar
WIP  
justinborromeo committed
229 230
        # regroup_layers assigns layers to the partitions.  Returns a list of
        # partition lists which contain layers.
harry1080ti's avatar
harry1080ti committed
231 232
        layer = self.regroup_layers(layer)

233
        return pid, self.eva_hybrid_sq(layer)[0]
harry1080ti's avatar
harry1080ti committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    def run(self):
        self.trial += self.trial
        if (self.seeding_type=="allzeros"):
            self.seed = [0]*(self.k-1)
            self.seed_od = self.seed
        elif (self.seeding_type=="optimised"):
            self.seed = []
            for i in range(self.k - 1):
                self.seed.append(int(len(self.layers)/self.k))
            self.seed.append(len(self.layers) - sum(self.seed))
            self.seed_od = self.seed
            self.seed = [self.encode(val, len(self.layers)) for val in self.seed[:-1]]
        else:
            raise ValueError('Invalid Seeding Strategy')

        self.es = cma.CMAEvolutionStrategy(self.seed, self.sigma, \
            {'popsize' : self.population_size})

        best_overall = self.penalty_offest
        self.i = 0
harry1080ti's avatar
harry1080ti committed
255
        temp_out = []
harry1080ti's avatar
harry1080ti committed
256 257 258 259 260 261 262 263
        while not self.es.stop() and self.i < self.max_iter:
            samples = self.es.ask()
            id_list = [(idx, sample) for idx, sample in enumerate(samples)]
            scores = [0] * self.es.popsize
            invalid_sampling = 0

            res_combintaions = [0] * self.es.popsize

harry1080ti's avatar
harry1080ti committed
264 265 266 267
            # pool = Pool(processes = cpu_count() - 4)
            # for result in pool.imap_unordered(self.evaluation_top_level, id_list):
            #     scores[result[0]] = result[1]
            #     if result[1] >= self.penalty_offest:
harry1080ti's avatar
harry1080ti committed
268
            #         invalid_sampling += 1
harry1080ti's avatar
harry1080ti committed
269
            #     else:
270
            #         if not self.is_hybrid:
harry1080ti's avatar
harry1080ti committed
271 272 273 274 275 276 277 278
            #             res_combintaions[result[0]] = result[2]
            # pool.close()
            # pool.join()

            for tup in id_list:
                _, scores[tup[0]] = self.evaluation_top_level(tup)
                if scores[tup[0]] >= self.penalty_offest:
                    invalid_sampling += 1
harry1080ti's avatar
harry1080ti committed
279

280
            if not self.is_hybrid:
harry1080ti's avatar
harry1080ti committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
                best_in_iteration = min(scores)

                if best_in_iteration < best_overall and best_in_iteration < self.penalty_offest:
                    best_overall = best_in_iteration
                    self.best_res = res_combintaions[scores.index(min(scores))]

            ##print(str(self.i) + ":", \
            #    "Sigma:",round(self.es.sigma, 4), \
            #    "|| Valid sampling percentage:", \
            #        (self.population_size - invalid_sampling) /self.population_size *100)
            ##print("invalid sampling", invalid_sampling)
            self.valid_sampling_percentage = (self.population_size - invalid_sampling) /self.population_size *100
            self.total_valid_solution += self.population_size - invalid_sampling
            self.samples = samples
            self.scores = scores
            self.es.tell(samples, scores)

            self.end = time.time()
            self.best_layer = [self.decode(val, len(self.layers)) for val in self.es.result[0]]
            self.best_layer.append(len(self.layers) - sum(self.best_layer))
301
            temp_out.append(self.report(False)[1])
harry1080ti's avatar
harry1080ti committed
302 303 304
            self.i += 1

        self.ending_iter = self.i
LongChan's avatar
LongChan committed
305
        return temp_out
harry1080ti's avatar
harry1080ti committed
306

307
    def report(self, output_png):
harry1080ti's avatar
harry1080ti committed
308 309 310 311 312
        ##print(self.i, self.es.sigma)
        max_latency = 0
        layer = []
        res = []
        latencies = []
Justin Borromeo's avatar
Justin Borromeo committed
313 314 315 316 317 318 319 320 321
        if not self.filter_layer(self.best_layer):
            ##print("RESULT NOT VALID")
            ##print("Layer:", self.best_layer, "sum: ", sum(self.best_layer))
            #print(self.penalty_layer(self.best_layer))
            if self.print_to_csv:
                with open(pc.RESULT_CSV_PATH+'cma_logmore_sq.csv', 'a') as csvFile:
                    writer = csv.writer(csvFile, delimiter=',', lineterminator="\n")
                    writer.writerow([self.target_col,self.i,self.k, self.topology_file, 0, 0, 0, 0, 0, 0, 0, layer, res, self.end-self.start, self.es.sigma, self.seed_od,self.valid_sampling_percentage, self.trial, self.population_size, self.max_res_unit, self.seeding_type])
                csvFile.close
harry1080ti's avatar
harry1080ti committed
322

Justin Borromeo's avatar
Justin Borromeo committed
323
            result = [self.target_col,self.i,self.k, self.topology_file, 0, 0, 0, 0, 0, 0, 0, layer, res, self.end-self.start, self.es.sigma, self.seed_od,self.valid_sampling_percentage, self.trial, self.population_size, self.max_res_unit, self.seeding_type]
harry1080ti's avatar
harry1080ti committed
324

Justin Borromeo's avatar
Justin Borromeo committed
325
            return False, result
harry1080ti's avatar
harry1080ti committed
326

Justin Borromeo's avatar
Justin Borromeo committed
327 328
        layer = self.regroup_layers(self.best_layer)
        max_latency, latencies, res, _ = self.eva_hybrid_sq(layer)
harry1080ti's avatar
harry1080ti committed
329

harry1080ti's avatar
harry1080ti committed
330
        # generate data for mapping the full array (129 * 129)
harry1080ti's avatar
harry1080ti committed
331 332 333
        full_latency, full_max_idx = self.find_max_latency([self.layers], [129]*len(self.layers))

        # PLEASE UNCOMMENT OUT THIS PART IF YOU NOT USING THE BASH SCRIPT WE HAVE PROVIDED 
harry1080ti's avatar
harry1080ti committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347
        # print("================================= RESULT =================================")
        # print("Solution: (out of", self.total_valid_solution, "solutions)")
        # print(layer)
        # print("Res mapping:")
        # print(res)
        # print("Latency for each partition: ")
        # print(latencies)
        # print("Final Latency:", max_latency*self.k, "|| Throught put:", 1/max_latency)
        # print("==========================================================================")
        # print("Map to full array (", self.max_res_unit, ")")
        # print("Final Latency:", full_latency[full_max_idx], "|| Throught put:", 1/full_latency[full_max_idx])
        # print("==========================================================================")
        # print("Throughtput Ratio:", (1/max_latency)/(1/full_latency[full_max_idx]))
        # print("Latency increase:", (max_latency*self.k)/full_latency[full_max_idx])
harry1080ti's avatar
harry1080ti committed
348

harry1080ti's avatar
harry1080ti committed
349 350 351 352 353
        if self.print_to_csv:
            with open(pc.RESULT_CSV_PATH+'cma_logmore_sq.csv', 'a') as csvFile:
                writer = csv.writer(csvFile, delimiter=',', lineterminator="\n")
                writer.writerow([self.target_col,self.i,self.k, self.topology_file, 1,(1/max_latency), max_latency*self.k, 1/full_latency[full_max_idx], full_latency[full_max_idx], (1/max_latency)/(1/full_latency[full_max_idx]), (max_latency*self.k)/full_latency[full_max_idx], layer, res, self.end-self.start, self.es.sigma, self.seed_od,self.valid_sampling_percentage, self.trial, self.population_size, self.max_res_unit, self.seeding_type])
            csvFile.close
harry1080ti's avatar
harry1080ti committed
354 355
        
        if self.valid_sampling_percentage > 0:
356 357 358
            directory_path = pc.RESULT_SCREENSHOT_PATH + \
                str(self.topology_file.replace(".csv", "")) + "/" + \
                "pack_size_" + str(self.max_pack_size) + "/" + \
Justin Borromeo's avatar
Justin Borromeo committed
359
                "penalty_constant_" + str(pp.PENALTY_CONSTANT) + "/"
360 361
            makedirs(directory_path, exist_ok = True)
            pngFileName = "k=" + str(self.k) + "_max=" + str(self.max_res_unit) \
Justin Borromeo's avatar
Justin Borromeo committed
362
                + "_latency=" + str(max_latency) + ".png"
Justin Borromeo's avatar
Justin Borromeo committed
363
            if pp.isPackable(res, self.max_pack_size) and output_png:
364 365 366 367 368 369 370 371
                bin_area = self.max_pack_size ** 2
                packed_area = 0
                for rect in res:
                    square_area = rect ** 2
                    packed_area += square_area
                percentage_wasted = 100 * (bin_area - packed_area) / bin_area
                consumed_area = 0
                pp.printPNG(res, self.max_pack_size, directory_path + pngFileName)
harry1080ti's avatar
harry1080ti committed
372
        
harry1080ti's avatar
harry1080ti committed
373 374
        result = [self.target_col,self.i,self.k, self.topology_file, 1,(1/max_latency), max_latency*self.k, 1/full_latency[full_max_idx], full_latency[full_max_idx], (1/max_latency)/(1/full_latency[full_max_idx]), (max_latency*self.k)/full_latency[full_max_idx], layer, res, self.end-self.start, self.es.sigma, self.seed_od,self.valid_sampling_percentage, self.trial, self.population_size, self.max_res_unit, self.seeding_type]
        return True, result
harry1080ti's avatar
harry1080ti committed
375 376 377 378 379 380 381 382 383 384 385 386

if __name__ == "__main__":
    import csv
    import sys

    topology = sys.argv[1]
    k = int(sys.argv[2])
    population_size = int(sys.argv[3])
    max_res_unit = int(sys.argv[4])
    seeding_type = sys.argv[5]
    target_col = sys.argv[6]

387
    es_hybrid = cma_approach(
harry1080ti's avatar
harry1080ti committed
388 389 390 391 392 393 394 395 396 397 398
        path_to_datasrc = str(topology)+"_square_mem_bound.csv",
        path_to_topology = str(topology)+".csv",
        target_col = str(target_col),

        number_of_partition = k, max_iteration = 10000,
        sigma = 0.5, population_size = population_size,

        max_res_unit = max_res_unit, initial_res = 0,
        res_step = 3,
        penalty_offest = 100000000000,
        seeding_type = seeding_type,
399
        hybrid = True,
harry1080ti's avatar
harry1080ti committed
400
        print_to_csv = True
harry1080ti's avatar
harry1080ti committed
401 402 403
    )

    trials = 1
404 405 406
    es_hybrid.run()
    while not es_hybrid.report(True) and trials < 20:
        es_hybrid.run()
harry1080ti's avatar
harry1080ti committed
407 408
        trials += 1

harry1080ti's avatar
harry1080ti committed
409
    # k += 1
harry1080ti's avatar
harry1080ti committed
410
    #print("convergence takes", trials, "trials")