|
| 1 | +/* |
| 2 | + * SonarQube Python Plugin |
| 3 | + * Copyright (C) 2011-2024 SonarSource SA |
| 4 | + * mailto:info AT sonarsource DOT com |
| 5 | + * |
| 6 | + * This program is free software; you can redistribute it and/or |
| 7 | + * modify it under the terms of the GNU Lesser General Public |
| 8 | + * License as published by the Free Software Foundation; either |
| 9 | + * version 3 of the License, or (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | + * Lesser General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU Lesser General Public License |
| 17 | + * along with this program; if not, write to the Free Software Foundation, |
| 18 | + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 | + */ |
| 20 | +package org.sonar.python.checks; |
| 21 | + |
| 22 | +import java.util.Collections; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Optional; |
| 25 | +import java.util.Set; |
| 26 | +import org.sonar.check.Rule; |
| 27 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 28 | +import org.sonar.plugins.python.api.symbols.Symbol; |
| 29 | +import org.sonar.plugins.python.api.symbols.Usage; |
| 30 | +import org.sonar.plugins.python.api.tree.Argument; |
| 31 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 32 | +import org.sonar.plugins.python.api.tree.Expression; |
| 33 | +import org.sonar.plugins.python.api.tree.Name; |
| 34 | +import org.sonar.plugins.python.api.tree.QualifiedExpression; |
| 35 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 36 | +import org.sonar.plugins.python.api.tree.Tree; |
| 37 | +import org.sonar.python.cfg.fixpoint.ReachingDefinitionsAnalysis; |
| 38 | +import org.sonar.python.tree.TreeUtils; |
| 39 | + |
| 40 | +@Rule(key = "S6982") |
| 41 | +public class TorchModuleModeShouldBeSetAfterLoadingCheck extends PythonSubscriptionCheck { |
| 42 | + private static final Set<String> STATE_SETTING_FUNCTION_FQNS = Set.of("eval", "train"); |
| 43 | + private static final String TORCH_LOAD_FQN = "torch.load"; |
| 44 | + private static final String LOAD_STATE_DICT_NAME = "load_state_dict"; |
| 45 | + private static final String MESSAGE = "Set the module in training or evaluation mode."; |
| 46 | + private static final int IS_TORCH_LOAD_CALL_MAX_RECURSIVE_COUNTER = 10; |
| 47 | + |
| 48 | + private ReachingDefinitionsAnalysis reachingDefinitionsAnalysis; |
| 49 | + |
| 50 | + @Override |
| 51 | + public void initialize(Context context) { |
| 52 | + context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> reachingDefinitionsAnalysis = |
| 53 | + new ReachingDefinitionsAnalysis(ctx.pythonFile())); |
| 54 | + |
| 55 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, ctx -> { |
| 56 | + CallExpression callExpr = (CallExpression) ctx.syntaxNode(); |
| 57 | + List<Usage> receiverUsages = getForwardUsages(callExpr); |
| 58 | + if (isLoadStateDictCall(callExpr) && !hasEvalOrTrainUsage(receiverUsages) && !isModelPassedOn(receiverUsages)) { |
| 59 | + ctx.addIssue(callExpr.callee(), MESSAGE); |
| 60 | + } |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + private boolean isLoadStateDictCall(CallExpression callExpr) { |
| 65 | + // To properly check if the correct load_state_dict is called, typeshed type information would be required. |
| 66 | + // Since this is currently not possible, we check if the parameter to load_state_dict is torch.load(...), |
| 67 | + // with the assumption that if torch.load is passed to this load_state_dict, it is probably the correct method |
| 68 | + if(callExpr.callee() instanceof QualifiedExpression qualifiedExpr) { |
| 69 | + return LOAD_STATE_DICT_NAME.equals(qualifiedExpr.name().name()) && containsTorchLoadCall(callExpr.arguments()); |
| 70 | + } |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + private boolean containsTorchLoadCall(List<Argument> args) { |
| 75 | + return args.stream() |
| 76 | + .flatMap(TreeUtils.toStreamInstanceOfMapper(RegularArgument.class)) |
| 77 | + .anyMatch(arg -> isTorchLoadCall(arg.expression(), 0)); |
| 78 | + } |
| 79 | + |
| 80 | + private boolean isTorchLoadCall(Expression expr, int recursiveCounter) { |
| 81 | + if (recursiveCounter > IS_TORCH_LOAD_CALL_MAX_RECURSIVE_COUNTER) { |
| 82 | + return false; |
| 83 | + } else if (expr instanceof CallExpression callExpr) { |
| 84 | + Symbol calleeSymbol = callExpr.calleeSymbol(); |
| 85 | + return calleeSymbol != null && TORCH_LOAD_FQN.equals(calleeSymbol.fullyQualifiedName()); |
| 86 | + } else if (expr instanceof Name name) { |
| 87 | + return reachingDefinitionsAnalysis.valuesAtLocation(name).stream() |
| 88 | + .anyMatch(definitionExpr -> isTorchLoadCall(definitionExpr, recursiveCounter + 1)); |
| 89 | + } else { |
| 90 | + return false; |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private static List<Usage> getForwardUsages(CallExpression callExpr) { |
| 95 | + List<Usage> usages = getFunctionCallReceiverName(callExpr) |
| 96 | + .flatMap(name -> Optional.ofNullable(name.symbol())) |
| 97 | + .map(Symbol::usages) |
| 98 | + .orElse(Collections.emptyList()); |
| 99 | + |
| 100 | + return usages.stream() |
| 101 | + .filter(usage -> usage.tree().firstToken().line() > callExpr.firstToken().line()) |
| 102 | + .toList(); |
| 103 | + } |
| 104 | + |
| 105 | + private static Optional<Name> getFunctionCallReceiverName(CallExpression callExpr) { |
| 106 | + return Optional.ofNullable(callExpr.callee()) |
| 107 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(QualifiedExpression.class)) |
| 108 | + .flatMap(qualifiedExpr -> Optional.ofNullable(qualifiedExpr.qualifier())) |
| 109 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(Name.class)); |
| 110 | + } |
| 111 | + |
| 112 | + private static boolean hasEvalOrTrainUsage(List<Usage> usages) { |
| 113 | + return usages.stream().anyMatch(TorchModuleModeShouldBeSetAfterLoadingCheck::isEvalOrTrain); |
| 114 | + } |
| 115 | + |
| 116 | + private static boolean isEvalOrTrain(Usage usage) { |
| 117 | + Tree callTree = TreeUtils.firstAncestorOfKind(usage.tree(), Tree.Kind.CALL_EXPR); |
| 118 | + if (callTree != null) { |
| 119 | + CallExpression usageCall = (CallExpression) callTree; |
| 120 | + Symbol usageCallSymbol = usageCall.calleeSymbol(); |
| 121 | + return usageCallSymbol != null && STATE_SETTING_FUNCTION_FQNS.contains(usageCallSymbol.name()); |
| 122 | + } |
| 123 | + return false; |
| 124 | + } |
| 125 | + |
| 126 | + private static boolean isModelPassedOn(List<Usage> usages) { |
| 127 | + return usages.stream().anyMatch(TorchModuleModeShouldBeSetAfterLoadingCheck::isPassingModel); |
| 128 | + } |
| 129 | + |
| 130 | + private static boolean isPassingModel(Usage usage) { |
| 131 | + return TreeUtils.firstAncestorOfKind(usage.tree(), Tree.Kind.CALL_EXPR) != null; |
| 132 | + } |
| 133 | +} |
0 commit comments