import torch
import argparse
from avalanche.benchmarks import PermutedMNIST, SplitMNIST
from avalanche.training.strategies import EWC
from avalanche.models import SimpleMLP
from avalanche.evaluation.metrics import ExperienceForgetting, \
    accuracy_metrics, loss_metrics, cpu_usage_metrics, timing_metrics, \
    gpu_usage_metrics, ram_usage_metrics
from avalanche.logging import InteractiveLogger, TextLogger
from avalanche.training.plugins import EvaluationPlugin

"""
This example tests EWC on Split MNIST and Permuted MNIST.
It is possible to choose, among other options, between EWC with separate
penalties and online EWC with a single penalty.

On Permuted MNIST EWC maintains a very good performance on previous tasks
with a wide range of configurations. The average accuracy on previous tasks
at the end of training on all task is around 85%,
with a comparable training accuracy.

On Split MNIST, on the contrary, EWC is not able to remember previous tasks and
is subjected to complete forgetting in all configurations. The training accuracy
is above 90% but the average accuracy on previou tasks is around 20%.
"""

def main(args):
    model = SimpleMLP(hidden_size=args.hs)
    optimizer = torch.optim.SGD(model.parameters(), lr=args.lr)
    criterion = torch.nn.CrossEntropyLoss()

    # check if selected GPU is available or use CPU
    assert args.cuda == -1 or args.cuda >= 0, "cuda must be -1 or >= 0."
    device = torch.device(f"cuda:{args.cuda}"
                          if torch.cuda.is_available() and
                          args.cuda >= 0 else "cpu")
    print(f'Using device: {device}')

    # create scenario
    if args.scenario == 'pmnist':
        scenario = PermutedMNIST(n_experiences=args.permutations)
    elif args.scenario == 'smnist':
        scenario = SplitMNIST(n_experiences=5, return_task_id=False)
    else:
        raise ValueError("Wrong scenario name. Allowed pmnist, smnist.")

    # choose some metrics and evaluation method
    interactive_logger = InteractiveLogger()
    text_logger = TextLogger(open('log.txt', 'a'))

    eval_plugin = EvaluationPlugin(
        accuracy_metrics(
            minibatch=True, epoch=True, experience=True, stream=True),
        loss_metrics(minibatch=True, epoch=True, experience=True, stream=True),
        cpu_usage_metrics(
            minibatch=False, epoch=True, experience=True, stream=True),
        #timing_metrics(
        #    minibatch=True, epoch=True, experience=True, stream=True),
        ram_usage_metrics(
            minibatch=False, epoch=True, experience=True, stream=True),
        gpu_usage_metrics(
            args.cuda, minibatch=False, epoch=True, experience=True, stream=True),
        ExperienceForgetting(),
        loggers=[interactive_logger, text_logger])

    # eval_plugin = EvaluationPlugin(
    #     accuracy_metrics(
    #         minibatch=True, epoch=True, experience=True, stream=True),
    #     loss_metrics(minibatch=True, epoch=True, experience=True, stream=True),
    #     ExperienceForgetting(),
    #     ram_usage_metrics(experience=True, epoch=True, stream=True),
    #     gpu_usage_metrics(args.cuda, every=0.5, experience=True, epoch=True, stream=True),
    #     loggers=[interactive_logger])

    # create strategy
    strategy = EWC(model, optimizer, criterion, args.ewc_lambda,
                   args.ewc_mode, decay_factor=args.decay_factor,
                   train_epochs=args.epochs, device=device,
                   train_mb_size=args.minibatch_size, evaluator=eval_plugin)

    # train on the selected scenario with the chosen strategy
    print('Starting experiment...')
    results = []
    for experience in scenario.train_stream:
        print("Start training on experience ", experience.current_experience)

        strategy.train(experience)
        print("End training on experience", experience.current_experience)
        print('Computing accuracy on the test set')
        results.append(strategy.eval(scenario.test_stream[:]))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--scenario', type=str,
                        choices=['pmnist', 'smnist'], default='smnist',
                        help='Choose between Permuted MNIST, Split MNIST.')
    parser.add_argument('--ewc_mode', type=str, choices=['separate', 'online'],
                        default='separate', help='Choose between EWC and online.')
    parser.add_argument('--ewc_lambda', type=float, default=0.4,
                        help='Penalty hyperparameter for EWC')
    parser.add_argument('--decay_factor', type=float, default=0.1,
                        help='Decay factor for importance when ewc_mode is online.')
    parser.add_argument('--lr', type=float, default=1e-3, help='Learning rate.')
    parser.add_argument('--hs', type=int, default=256, help='MLP hidden size.')
    parser.add_argument('--epochs', type=int, default=10,
                        help='Number of training epochs.')
    parser.add_argument('--minibatch_size', type=int, default=128,
                        help='Minibatch size.')
    parser.add_argument('--permutations', type=int, default=5,
                        help='Number of experiences in Permuted MNIST.')
    parser.add_argument('--cuda', type=int, default=0,
                        help='Specify GPU id to use. Use CPU if -1.')
    args = parser.parse_args()

    main(args)
@@ -269,87 +269,8 @@
 rics
-, cpu_usage_metrics, timing_metrics, %5C%0A    gpu_usage_metrics, ram_usage_metrics
 %0Afro
@@ -2144,980 +2144,115 @@
 ics(
-minibatch=True, epoch=True, experience=True, stream=True),%0A        cpu_usage_metrics(%0A            minibatch=False, epoch=True, experience=True, stream=True),%0A        #timing_metrics(%0A        #    minibatch=True, epoch=True, experience=True, stream=True),%0A        ram_usage_metrics(%0A            minibatch=False, epoch=True, experience=True, stream=True),%0A        gpu_usage_metrics(%0A            args.cuda, minibatch=False, epoch=True, experience=True, stream=True),%0A        ExperienceForgetting(),%0A        loggers=%5Binteractive_logger, text_logger%5D)%0A%0A    # eval_plugin = EvaluationPlugin(%0A    #     accuracy_metrics(%0A    #         minibatch=True, epoch=True, experience=True, stream=True),%0A    #     loss_metrics(minibatch=True, epoch=True, experience=True, stream=True),%0A    #     ExperienceForgetting(),%0A    #     ram_usage_metrics(experience=True, epoch=True, stream=True),%0A    #     gpu_usage_metrics(args.cuda, every=0.5, experience=True, epoch=True, stream=True),%0A    #
+%0A            minibatch=True, epoch=True, experience=True, stream=True),%0A        ExperienceForgetting(),%0A   
     

Reset EWC to less verbose logging